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

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