I have a struct for holding data;
struct MyStruct {
var age: Int
var name: String
}
I make an array of this and fill it with data;
var myArray = [MyStruct]()
myArray[0] = MyStruct(age: 26, name: "John")
myArray[1] = MyStruct(age: 35, name: "Smith")
How can I find the index of the element in myArray
that contains the name "Smith"?
Edit: Here's more context about where I need to find the location using the new code from Losiowaty;
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let selection = tableView.cellForRow(at: indexPath)?.textLabel
let name = selection!.text!
let location = myArray.index(where: { $0.name == name})
//additional code to comply with the function and return, unneeded for this context
}
You can use index(where:)
method. A quick example :
let index = myArray.index(where: { $0.name == "Smith" })
In a case when there would be no such element, the method will return nil
.
With more context from edits, the best (i.e. safest) way would be something like this :
if let name = selection?.name {
if let location = myArray.index(where: { $0.name == name }) {
// you know that location is not nil here
}
}
Source - https://developer.apple.com/reference/swift/array/1688966-index
For Swift 4: index(where:) has been deprecated, so now use firstIndex:
let index = firstIndex(where: { $0.name == "Smith" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With