1

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?

1
  • 2
    I do not understand the title. Can you change it to eliminate the misleading "max/min value"? Your question is not about that at all. Commented Nov 8, 2014 at 11:41

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Note: Optional<Int> and Int? are different way to express the same thing: an optional. Reading your answer it looks like they are different instead. I would make that explicit, just to avoid confusion
@mstysf genius! It worked! I don't understand the type of export that find gives as output, why it shouldn't be just as the type of the value found in the array. Thank you so much anyway
Optionals are to deal with nothing case or error case. An optional value contains either a value or nil. In order to extract its value you need to use if-let syntax or ! operator to force optional to unwrap. But you have to be careful when you use ! operator. If optional value contains nil it will crash your program. In your case think about an array [1,2,3,4,5] and what happens when you call find(array, 20). Because there is no '20' in array it is logical to return nil. Because find function can return nil or a value the return type is Int? not Int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.