Swift – How to find index of list item in Swift

arraysswift

I am trying to find an item index by searching a list. Does anybody know how to do that?

I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").

Best Answer

As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3