Swift - Statement Switches


A switch statement runs code depending on the value of a variable.

To run code based on the value of an integer, use a switch statement like this:


let integerSwitch = 3 
switch integerSwitch { 
case 0: // w  ww  . jav a 2s  . c  o m
    print("It's 0") 
case 1: 
    print("It's 1") 
case 2: 
    print("It's 2") 
    print("It's something else") 


Switches in Swift have to be exhaustive.

The switch statement must cover all possible values.

If you're switching using a Bool type, which can either be true or false, you must provide handlers for both values.

If you don't, it's a compiler error.

The switch statement has a default case, which is shorthand for "every other possible value."

Related Topics