Nicholas Nicholas - 28 days ago 5
iOS Question

Find the index of a certain value in array using swift

Following the instructions reported in the documented swift manual
http://swift-ios.co/standard-functions-in-swift/

I found the code the extract the index of a certain value of an array using

var languages = ["Swift", "Objective-C"]
find(languages, "Objective-C") == 1
find(languages, "Java") == nil
find([29, 85, 42, 96, 75], 42) == 2


The problem is that the output value doesn' t have the same type of the elements os the starting array, since the output in the console is (for the last line)

Optional(2)


What if I want to get the 2 as
Int
or
Double
?

Answer

It is Int? (a.k.a. Optional<Int>). You need to extract Int from it. You can use if-let syntax

if let index = find([29, 85, 42, 96, 75], 42) {
    // index is Int
}
Comments