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")
.
Any of this solution works for me
This the solution i have for Swift 4 :
Swift 4.2
Example1
Example2
You can also use the functional library Dollar to do an indexOf on an array as such http://www.dollarswift.org/#indexof-indexof
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:
Update for Swift 2.0:
The old
find
function is not supported any more with Swift 2.0!With Swift 2.0,
Array
gains the ability to find the index of an element using a function defined in an extension ofCollectionType
(whichArray
implements):Additionally, finding the first element in an array fulfilling a predicate is supported by another extension of
CollectionType
:Note that these two functions return optional values, as
find
did before.Update for Swift 3.0:
Note the syntax of indexOf has changed. For items conforming to
Equatable
you can use:A detailed documentation of the method can be found at https://developer.apple.com/reference/swift/array/1689674-index
For array items that don't conform to
Equatable
you'll need to useindex(where:)
:Update for Swift 4.2:
With Swift 4.2,
index
is no longer used but is separated intofirstIndex
andlastIndex
for better clarification. So depending on whether you are looking for the first or last index of the item:Update for Swift 2:
Swift 1:
If you're looking just to check if an element is contained inside an array, that is, just get a boolean indicator, use
contains(sequence, element)
instead offind(array, element)
:See example below: