Is there a method called indexof or something similar?
var array = ["Jason", "Charles", "David"] indexOf(array, "Jason") // Should return 0
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.
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 .
A set is a collection of unordered unique values. Therefore, it cannot contain a duplicate element.
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With