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

Using optional binding

We should avoid forced unwrapping of optionals as there is rarely any need to do this. We should prefer optional binding or optional chaining over forced unwrapping.

The following examples show the preferred and non-preferred methods where the myOptional variable is defined as an optional:

//Preferred Method Optional Binding 
 if let value = myOptional { 
  // code if myOptional is not nil 
} else { 
  // code if myOptional is nil 
} 
 
//Non-Preferred Method  
if myOptional != nil { 
  // code if myOptional is not nil 
} else { 
  //  code if myOptional is nil 
} 

If there is more than one optional that we need to unwrap, we should include them in the same if-let or guard statement, rather than unwrapping them on separate lines. There are ...

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