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

The fallthrough statement

In Swift, the switch statement does not fall through like other languages; however, we can use the fallthrough statement to force them to fall through. The fallthrough statement can be very dangerous because, once a match is found, the next case defaults to true and that code block is executed. The following example illustrates this:

var name = "Jon" 
var sport = "Baseball" 
switch sport { 
  case "Baseball": 
    print("\(name) plays Baseball")  
    fallthrough 
  case "Basketball": 
    print("\(name) plays Basketball")  
    fallthrough 
  default: 
    print("Unknown sport") 
} 

In the preceding example, the baseball case was matched, however, there was a fallthrough keyword in both the baseball and basketball case; therefore, all three cases 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