Grouping Switch Statement Cases Together - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.16 Grouping Switch Statement Cases Together

Problem

You want to design your cases in a switch statement so that some of them fall through to the others.

Solution

Use the fallthrough syntax. Here is an exmaple:

let age = 30

switch age{

case 1...10:

fallthrough

case 20...30:

print("Either 1 to 10 or 20 to 30")

default:

print(age)

}

NOTE

This is just an example. There are better ways of writing this code than to use fallthrough. You can indeed batch these two cases together into one case statement.

Discussion

In Swift, if you want one case statement to fall through to the next, you have to explicitly state the fallthrough command. This is more for the programmers to look at than the compiler, because in many langauges the compiler is able to fall through to the next case statement if you just leave out the break statement. However, this is a bit tricky because the developer might have just forgotten to place the break statement at the end of the case and all of a sudden her app will start behaving really strangely. Swift now makes you request fall-through explicity, which is safer.

See Also