milkcup milkcup - 5 months ago 11
Swift Question

Why does Optional Binding evaluate to type Bool?

Why is this variable i not substituted for Bool but optional binding is?
Swift claims this in the guide..


Swift’s type safety prevents non-Boolean values from being substituted
for Bool. The following example reports a compile-time error:


let i = 1
if i {
// this example will not compile, and will report an error
}


Yet this compiles

var foo: String?

if let bar = foo {
print("Non nil")
}

Answer

An optional is essentially an enum with two possible values either a designated value, in your example a string, or nil. An if let binding is not being substituted for a Bool in your example. Instead, it is checking if the variable foo is nil and if it is not nil then it sets bar equal to foo and performs the code inside the block. An if let binding is thus essentially a shortcut for

var foo: String?
if foo != nil {
   //Set bar equal to the unwrapped value of foo
   let bar = foo!
   //Do whatever
}

The efficiency of this is best shown in a case where you would want to check if something is nil and check some characteristic of the value if it is not nil. Say you wanted to also check that foo has more than 5 characters and if it does then do something. Since foo could be nil you would have to check for it specifically to ensure it is not. An if let binding will let you do this:

if let bar = foo where bar.characters.count > 5 {
    print(bar)
}

rather than this:

 if foo != nil && foo?.characters.count > 5 {
   let bar = foo!
   print(bar)
 }

It basically makes very readable, and thus more maintainable code. Also, it prevents you from having to unwrap the optional manually (the ! operator at the end of foo).