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")
.
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")
.
For custom class, you need to implement the Equatable protocol.
For SWIFT 3 you can use a simple function
This will give the number position, so you can use like
Hope to be useful
Swift 4
For reference types:
Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code
Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.
I think it's worth mentioning that with reference types (
class
) you might want to perform an identity comparison, in which case you just need to use the===
identity operator in the predicate closure:Swift 4 / Swift 3:
Note that the above syntax uses trailing closures syntax, and is equivalent to:
Swift 2 - the
index
function syntax used to be:* Note the relevant and useful comment by paulbailey about
class
types that implementEquatable
, where you need to consider whether you should be comparing using===
(identity operator) or==
(equality operator). If you decide to match using==
, then you can simply use the method suggested by others (people.index(of: person1)
).SWIFT 4
Let's say you want to store a number from the array called cardButtons into cardNumber, you can do it this way:
sender is the name of your button