Swift - Statement Switches

Introduction

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:

Demo

let integerSwitch = 3 
switch integerSwitch { 
case 0: /*  ww w  .j a va2  s .  c  om*/
    print("It's 0") 
case 1: 
    print("It's 1") 
case 2: 
    print("It's 2") 
default: 
    print("It's something else") 
}

Result

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