-4

The code result is:
num1 is Optional(5)
num2 is Optional(5)
num2 is 5
I want to know why in if{} num2 is an optional value, but print "num2 is 5"

var optionalNum : Int? = 5
let num1 = optionalNum
print("num1 is \(num1)")

if let num2 = optionalNum {
    print("num2 is \(optionalNum)")
    print("num2 is \(num2)")
} else {
    print("optionalNum does not hold a value")

}
Athos-SPC
  • 3
  • 1
  • 2
    because in this line `if let num2 = optionalNum {` you just _unwrapped_ `optionalNum` into `num2`, which is not an optional anymore. – holex Nov 09 '16 at 13:49
  • 1
    I would highly recommend reading the [Optionals section of the Swift Programming Language Guide](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330) (specifically Optional Binding) – Hamish Nov 09 '16 at 13:51
  • There is also an excellent SO Documentation page about this subject, http://stackoverflow.com/documentation/swift/475/conditionals/1560/optional-binding-and-where-clauses#t=201611091355361786641 – milo526 Nov 09 '16 at 13:56

1 Answers1

1

When you write

if let num2 = optionalNum { ...

You are performing an optional binding.

In plain english it means

If optionalNum contains a value, then

  1. create a new constant num2 containing that value
  2. AND execute the block inside the { ... }
  3. AND make available the new num2 constant inside the block

So inside the block num2 is NOT an optional. So when you print it you get the plain value. This is the reason why it prints

num2 is 5
Community
  • 1
  • 1
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148