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")
.
While
indexOf()
works perfectly, it only returns one index.I was looking for an elegant way to get an array of indexes for elements which satisfy some condition.
Here is how it can be done:
Swift 3:
Swift 2:
Swift 2.1
Swift 3
If you are still working in Swift 1.x
then try,
In Swift 4, if you are traversing through your DataModel array, make sure your data model conforms to Equatable Protocol , implement the lhs=rhs method , and only then you can use ".index(of" . For example
And then,
In Swift 2 (with Xcode 7),
Array
includes anindexOf
method provided by theCollectionType
protocol. (Actually, twoindexOf
methods—one that uses equality to match an argument, and another that uses a closure.)Prior to Swift 2, there wasn't a way for generic types like collections to provide methods for the concrete types derived from them (like arrays). So, in Swift 1.x, "index of" is a global function... And it got renamed, too, so in Swift 1.x, that global function is called
find
.It's also possible (but not necessary) to use the
indexOfObject
method fromNSArray
... or any of the other, more sophisticated search meth dis from Foundation that don't have equivalents in the Swift standard library. Justimport Foundation
(or another module that transitively imports Foundation), cast yourArray
toNSArray
, and you can use the many search methods onNSArray
.You can
filter
an array with a closure:And you can count an array:
So you can determine if an array includes your element by combining these:
If you want to find the position, I don't see fancy way, but you can certainly do it like this:
EDIT
While we're at it, for a fun exercise let's extend
Array
to have afind
method:Now we can do this: