Switch in Swift

Switch statements express conditionals across many branches.

Here’s a basic switch.

import Foundation

let i = 2
print("Write \(i) as", terminator: " ")
switch i {
case 1:
    print("one")
case 2:
    print("two")
case 3:
    print("three")
default:
    break
}

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

switch Calendar.current.component(.weekday, from: Date()) {
case 7, 1:
    print("It's the weekend")
default:
    print("It's a weekday")
}

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

let t = Date()
let hour = Calendar.current.component(.hour, from: t)
switch hour {
case ..<12:
    print("It's before noon")
default:
    print("It's after noon")
}

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause.

func whatAmI(_ i: Any) {
    switch i {
    case is Bool:
        print("I'm a bool")
    case is Int:
        print("I'm an int")
    default:
        print("Don't know type \(type(of: i))")
    }
}

whatAmI(true)
whatAmI(1)
whatAmI("hey")
$ swiftc switch.swift && ./switch
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String