Swift only truly verifies that a switch
block is exhaustive when working with enum
types. Even a switching on Bool
requires a default
block in addition to true
and false
:
var b = true
switch b {
case true: println("true")
case false: println("false")
}
// error: switch must be exhaustive, consider adding a default clause
With an enum
, however, the compiler is happy to only look at the two cases:
enum MyBool {
case True
case False
}
var b = MyBool.True
switch b {
case .True: println("true")
case .False: println("false")
}
If you need to include a default
block for the compiler’s sake but don’t have anything for it to do, the break
keyword comes in handy:
var b = true
switch b {
case true: println("true")
case false: println("false")
default: break
}