Athos-SPC Athos-SPC - 1 year ago 87
Swift Question

In swift when print optional value when non optional

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")


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download