arrays - How to find index of list item in Swift? -
i trying find item index searching list. know how that?
i see there list.startindex , list.endindex bu want python's list.index("text")
as swift in regards more functional object-oriented (and arrays structs, not objects), use function "find" operate on array, returns optional value, prepared handle nil value:
let arr:array = ["a","b","c"] find(arr, "c")! // 2 find(arr, "d") // nil
update swift 2.0:
the old find
function not supported more swift 2.0!
with swift 2.0, array
gains ability find index of element using function defined in extension of collectiontype
(which array
implements):
let arr = ["a","b","c"] let indexofa = arr.indexof("a") // 0 let indexofb = arr.indexof("b") // 1 let indexofd = arr.indexof("d") // nil
additionally, finding first element in array fulfilling predicate supported extension of collectiontype
:
let arr2 = [1,2,3,4,5,6,7,8,9,10] let indexoffirstgreaterthanfive = arr2.indexof({$0 > 5}) // 5 let indexoffirstgreaterthanonehundred = arr2.indexof({$0 > 100}) // nil
note these 2 functions return optional values, find
did before.
update swift 3.0:
note syntax of indexof has changed. items conforming equatable
can use:
let indexofa = arr.index(of: "a")
a detailed documentation of method can found @ https://developer.apple.com/reference/swift/array/1689674-index
for array items don't conform equatable
you'll need use index(where:)
:
let index = cells.index(where: { (item) -> bool in item.foo == 42 // test if item you're looking })
Comments
Post a Comment