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
}
ageandnamein yourmyStructto useless values? 3) Why ismyArrayinitialized with an emptymyStruct?myArray.appendbased on user input later.= Int()and= String()on the two properties. 3) You want[MyStruct], not[MyStruct()]. The first declares an empty array that will contain instances ofMyStruct. The seconds declares an array containing one instance ofMyStruct.