Barnash Barnash - 1 year ago 136
Swift Question

How can I find the index of an item in Swift?

Is there a method called indexof or something similar?

var array = ["Jason", "Charles", "David"]

indexOf(array, "Jason") // Should return 0

Answer Source

EDIT: As of Swift 3.0, you should use the .index(where:) method instead and follow the change in the Swift 2.0 edit below.

EDIT: As of Swift 2.0, you should use the indexOf method instead. It too returns nil or the first index of its argument.

if let i = array.indexOf("Jason") {
    print("Jason is at index \(i)")
} else {
    print("Jason isn't in the array")

Use the find function. It returns either nil (if the value isn't found) or the first index of the value in the array.

if let i = find(array, "Jason") {
    println("Jason is at index \(i)")
} else {
    println("Jason isn't in the array")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download