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") 
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset