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 chaining instead of optional binding for multiple unwrapping

When we need to unwrap multiple layers, we should use optional chaining over multiple optional binding statements. The following example shows the preferred and non-preferred methods:

//Preferred Method 
if let color = jon.pet?.collar?.color {  
  print("The color of the collar is \(color)") 
} else { 
  print("Cannot retrieve color") 
} 
 
//Non-Preferred Method 
if let tmpPet = jon.pet, let tmpCollar = tmpPet.collar{  
  print("The color of the collar is \(tmpCollar.color)") 
} else { 
  print("Cannot retrieve color") 
} 

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