Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Index of Array containing Structs by searching for Struct Value using Swift 3.0

Tags:

swift

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
}
like image 399
kingfoot Avatar asked Dec 14 '16 22:12

kingfoot


2 Answers

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

like image 80
Losiowaty Avatar answered Nov 23 '22 19:11

Losiowaty


For Swift 4: index(where:) has been deprecated, so now use firstIndex:

let index = firstIndex(where: { $0.name == "Smith" })
like image 37
SafeFastExpressive Avatar answered Nov 23 '22 19:11

SafeFastExpressive