Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the index of an item in Swift? [duplicate]

Tags:

swift

Is there a method called indexof or something similar?

var array = ["Jason", "Charles", "David"]  indexOf(array, "Jason") // Should return 0 
like image 813
Barnash Avatar asked Jun 08 '14 10:06

Barnash


People also ask

How do you find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

How do you find the index of an item in an array in Swift?

To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter. Array. firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil .

Can set have duplicate values Swift?

A set is a collection of unordered unique values. Therefore, it cannot contain a duplicate element.


1 Answers

EDIT: As of Swift 3.0, you should use the .index(where:) method instead and follow the change in the Swift 2.0 edit below.

EDIT: As of Swift 2.0, you should use the indexOf method instead. It too returns nil or the first index of its argument.

if let i = array.indexOf("Jason") {     print("Jason is at index \(i)") } else {     print("Jason isn't in the array") } 

Use the find function. It returns either nil (if the value isn't found) or the first index of the value in the array.

if let i = find(array, "Jason") {     println("Jason is at index \(i)") } else {     println("Jason isn't in the array") } 
like image 117
nathan Avatar answered Sep 18 '22 07:09

nathan