O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required