Search code examples
xcodeswiftoption-typeoptional-binding

unable to use optional int "possibleNumber" in optional binding


I'm new to Swift and is trying to learn the concept of optional binding. I have came up with the following code:

let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber){
    print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
    print("\(possibleNumber) could not be converted to an int")
}

Xcode playground output error message:

value of optional type "int?" not unwrapped, did you mean to use "!" or "?"

However, when I added the "!" to if let actualNumber = Int(possibleNumber!){

let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber!){
    print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
    print("\(possibleNumber) could not be converted to an int")
}

Xcode display another error message:

initialiser for conditional binding must have Optional type, not int

Why is this happening?


Solution

  • The result of

    let possibleNumber = Int("123")
    

    is an optional Int - Int?

    Then you're trying to create another Int with

    Int(possibleNumber)
    

    which does not work because the initializer expects a non-optional type. The error message is related to the initializer rather than to the optional binding.

    Try this to get the same error message.

    let possibleNumber = Int("123")
    let x = Int(possibleNumber)
    

    In your second example when you initialize an Int with an implicit unwrapped Int! argument you get a non-optional Int and the compiler complains about the missing optional.