Optional binding

Optional binding is the recommended way to unwrap an optional. With optional binding, we perform a check to see whether the optional contains a valid value and, if so, unwrap it into a temporary variable or constant. This is all performed in one step.

Optional binding is performed with the if or while conditional statements. It takes the following format if we want to put the value of the optional in a constant:

if let constantName = optional { 
  statements 
} 

If we need to put the value in a variable, instead of a constant, we can use the var keyword, as shown in the following example:

if var variableName = optional { 
  statements 
} 

The following example shows how to perform optional binding:

var myString3: String? 
myString3 = "Space" 
if let tempVar = myString3 { 
  print(tempVar) 
} else { 
  print("No value") 
} 

In the example, we define the myString3 variable as an optional type. If the myString3 optional contains a valid value, then we set the new variable named tempvar to that value and print it to the console. If the myString3 optional does not contain a value, then we print No value to the console.

We are able to use optional binding to unwrap multiple optionals within the same optional binding line. For example, if we had three optionals named optional1, optional2, and optional3, we could use the following code to attempt to unwrap all three at once:

if let tmp1 = optional1, let tmp2 = optional2, let tmp3 = optional3 { 
} 

If any of the three optionals are nil, the whole optional binding statement fails. It is also perfectly acceptable with optional binding to assign the value to a variable of the same name. The following code illustrates this:

 

if let myOptional = myOptional {
print(myOptional) } else { print("myOptional was nil") }

One thing to note is that the temporary variable is scoped only for the conditional block and cannot be used outside it. To illustrate the scope of the temporary variable, let's take a look at the following code:

 

var myOptional: String?  
myOptional = "test" 
if var tmp = myOptional { 
  print("Inside:(tmp)") 
} 
// This next line will cause a compile time error  
print("Outside: (tmp)") 

This code would not compile because the tmp variable is only valid within the conditional block and we are attempting to use it outside it.

Using optional binding is a lot cleaner and easier than manually verifying that the optional has a value and using forced unwrapping to retrieve the value of the optional.

..................Content has been hidden....................

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