Search code examples
iosswiftxcodeswift3

Swift - How to search an array of structs


I have an array of such , such:

struct elephants {
 var name: String
 var age: Int
 var location: String
}

I then have an array of structs

var elephantArray [elephants] = [elephant1, elephant2, elephant3]

What I want to be able to do is to search based on elephants.name - so if elephant2.name was "Bob" then when I searched the array based on the name "Bob" then it would return the index position of elephant2.

How would I go about doing this?


Solution

  • Here's simple func which will help you:

    func searchElephantIndex(name: String, elephArray: [elephants]) -> Int? {
      return elephArray.firstIndex { $0.name == name }
    }
    

    If the elephant with the requested name does not exist, the function will return nil.