Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of list item in Swift?

Tags:

arrays

swift

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").

like image 551
Chéyo Avatar asked Jun 04 '14 04:06

Chéyo


People also ask

How do I index an array in Swift?

To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)

What is index in Swift?

Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

Which of the following function returns the index of an item along with its value in Swift?

Just use firstIndex method.

How do I filter an array in Swift?

To filter an array in Swift: Call the Array. filter() method on an array. Pass a filtering function as an argument to the method.


1 Answers

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:

let arr:Array = ["a","b","c"] find(arr, "c")!              // 2 find(arr, "d")               // nil 

Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item:

let arr = ["a","b","c","a"]  let indexOfA = arr.firstIndex(of: "a") // 0 let indexOfB = arr.lastIndex(of: "a") // 3 
like image 121
Sebastian Schuth Avatar answered Oct 04 '22 16:10

Sebastian Schuth