0

I've recently started learning swift 2 (having not used swift 1) and am trying to get my head around optionals and unwrapping. I've been trying to do a simple example that converts an optional String to an int. The example I have is below

var numbers: [String] = ["1","2","3","4"];

func findNumber (num:String, numbers:[String]) -> String?{
    for tempNum in numbers {
        if(tempNum == num){
            return tempNum;
        }
    }
    return nil;
}


if let s = findNumber("5", numbers: numbers), num = Int(s){
    print("found")
}else{
    print("not found")
}

if let num = Int(findNumber("5", numbers: numbers)?){
    print("found")
}else{
    print("not found")
}

After looking at How do you convert optional text input to Int in Swift 2, Xcode 7 beta using if let - toInt does not work I managed to get the first if statement working, but this seems like a bit of an extra step - create a variable to hold the optional result and then pass this in to the findNumber function. Why is it not possible to do something more concise like in the second example? Surely in both examples the value passed to the Int() function is nil? If I use ! to unwrap the return, and as long as it's a valid number I get the correct response, but I get an exception when using an invalid input such as "5".

Could this be written anymore concisely or is this just the behaviour of the language?

thanks

1
  • This is the correct/safe way for unwrapping in this situation. Commented Oct 8, 2015 at 11:02

1 Answer 1

0

Actually you are right, and that is why guard syntax is introduced in swift 2.0.

Consider my example below, i think it is more readable this way..

var numbers: [String] = ["1","2","3","4"];

func findNumber (num:String, numbers:[String]) -> String?{
    for tempNum in numbers {
        if(tempNum == num){
            return tempNum;
        }
    }
    return nil;
}

func isFound() {
    let s = findNumber("5", numbers: numbers)
    guard s != nil else {
        print("not found")
        return
    }
    // Confidently unwrap s
    print(s!)

    print("found")
}

isFound()
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for replying, the issue I'm seeing here though is the conversion between string to Int using the return value, in your reply you don't do any conversion ( i appreciate it's just a print so there is no need for conversion but it was just to provide a trivial example) in which case 'if let num = findNumber("5", numbers: numbers)' is fine and concise enough for me. What I'm asking in this instance is why is it fine to pass 's' to the 'Int()' function where 's' is the return value of the 'findNumber' function, but I can't pass 'findNumber()' directly into 'Int()' and get the same result

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.