-1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

1

In the if let construct

if let actualNumber = Int(possibleNumber!){
    print("\(possibleNumber) has an integer value of \(actualNumber)")
}

you don't need to use the Int initializer. You simply need to write

if let actualNumber = possibleNumber {
    print("\(possibleNumber) has an integer value of \(actualNumber)")
}

Now Swift will try to unwrap possibleNumber. If the operation does succeed the unwrapped value is put inside actualNumber and the THEN block executed.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Am I correct in saying, for the second example, the statement, if let actualNumber = Int(possibleNumber), actualNumber is expected to be of a optional type, however, Int(possibleNumber!) is equal to a non-optional int type, and this is the reason why XCode is complaining? – Thor Feb 25 '16 at 10:57