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 switch rather than multiple if statements

Wherever possible, we should prefer to use a single switch statement over multiple if statements. The following example shows the preferred and non-preferred methods:

//Preferred Method let speed = 300_000_000  
switch speed { 
  case 300_000_000: 
    print("Speed of light")  
  case 340: 
    print("Speed of sound")  
  default: 
    print("Unknown speed") 
} 
 
//Non-preferred Method let speed = 300_000_000  
if speed == 300_000_000 { 
  print("Speed of light") 
} else if speed == 340 {  
  print("Speed of sound") 
} else { 
  print("Unknown speed") 
}

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