Optional binding

Optional binding is used to check whether an optional variable or constant has a non-nil value, and if so, assign that value to a temporary, non-optional variable. For optional binding, we use the if let or if var keywords together. If we use if let, the temporary value is a constant and cannot be changed. If we use the if var keyword, it puts the temporary value into a variable that can be changed. The following code illustrates how optional binding is used:

var myOptional: String? 
if let temp = myOptional { 
  print(temp) 
  print("Can not use temp outside of the if bracket") 
} else { 
  print("myOptional was nil") 
} 

In the preceding example, we use the if let keywords to check whether the myOptional variable is nil. If it is not nil, we assign the value to the temp variable and execute the code between the brackets. If the myOptional variable is nil, we execute the code in the else bracket, which prints out the message, myOptional was nil. One thing to note is that the temp variable is scoped only for the conditional block and cannot be used outside the conditional block.

It is perfectly acceptable, and preferred with optional binding, to assign the value to a variable of the same name. The following code illustrates this:

var myOptional: String? 
if let myOptional = myOptional { 
  print(myOptional) 
  print("Cannot use temp outside of the if bracket") 
} else { 
  print("myOptional was nil") 
} 

To illustrate the scope of the temporary variable, let's look at the following code:

var myOptional: String?  
myOptional = "Jon" 
if var myOptional = myOptional { 
  myOptional = "test"  
  print("Inside:  (myOptional)") 
} 
print("Outside: (myOptional)") 

In this example, the first line that is printed to the console is Inside: test, because we are within the scope of the if var statement where we assign the value of test to the myOptional variable. The second line that is printed to the console is Outside: Optional(Jon) because we are outside the scope of the if var statement where the myOptional variable is set to Jon.

We can also test multiple optional variables in one line. We do this by separating each optional check with a comma. The following example shows how to do this:

if let myOptional = myOptional, let myOptional2 = myOptional2, let myOptional3 = myOptional3 { 
  // only reach this if all three optionals 
  // have non-nil values 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset