Using Switch statement in Swift?

Posted by Wei on June 28, 2017

What is Switch statement?

According to Swift document, a switch statement is:

A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.

Basiclly speaking, in a switch statement, it will try all possible values for a variable. Also, a switch statement must have a default value.

All the following code are based on Swift 3.0.

A Simple Example

Output is Ten for the example below.

Swift program that uses switch

let id = 10

switch id {
case 9:
    print("Nine")
case 10:
    print("Ten")
case 11:
    print("Eleven")
default:
    break
}

Multiple Case Values Example

Output is Medium for the example below.

Swift program that uses multiple case values

let size = 3

// Switch on the size Int.
switch size {
case 0, 1:
    // Two values match Small.
    print("Small")
case 2, 3:
    // Two values match Medium.
    print("Medium")
case 4, 5:
    // Two values match Large.
    print("Large")
default:
    break
}

Ranges Example

Output is Upper half for the example below.

Swift program that uses ranges in cases

let code = 70

// Switch based on ranges.
switch code {
case 0...50:
    print("Lower half")
case 51...100:
    print("Upper half")
default:
    print("Invalid")
}

Fallthrough Example

Fallthrough means that control proceeds to the next case in a switch, and the next case is entered even if the value does not match.

Output is below for the following example.

Number contains 2
Number contains 1
Number contains 0

Swift program that uses fallthrough statements

let size = 2
// Use switch with fallthrough statements.
switch size {
case 3:
    // This case will execute statements in case 2, 1 and 0.
    print("Number contains 3")
    fallthrough
case 2:
    print("Number contains 2")
    fallthrough
case 1:
    print("Number contains 1")
    fallthrough
case 0:
    print("Number contains 0")
default:
    print("Invalid")
}

String Example

Output is Is cat for the example below.

Swift program that uses switch on string

let name = "cat"

// Switch on the name string.
switch name {
case "bird":
    print("Is bird")
case "dog":
    print("Is dog")
case "cat":
    print("Is cat") // This is printed.
default:
    print("Something else")
}

Where Example

Where method can do further checking in some cases. For instance, we want to print out a tuple argument with a integer greater than 10. The following code output is below.

Default
Number = 15, Letter = b

Swift program that uses where in switch case

func test(code: (Int, Character)) {
    // Switch on the tuple argument.
    // We use let to allow the tuple items to be referenced.
    // We use where to test a part of the tuple.
    switch code {
    case let(number, letter) where number >= 10:
        print("Number = \(number), Letter = \(letter)")
    default:
        print("Default")
    }
}

// Call test with a tuple argument.
test(code: (5, "a"))
// Call test again.
test(code: (15, "b"))

Tuple Example

We use a “tuple pattern” to match all items in the tuple.

Output is Is xyz200 for the example below.

Swift that uses tuple switch

let data = ("xyz", 200)

// Match complete tuple values.
switch (data) {
    case ("abc", 300): print("Is abc300")
    case ("xyz", 200): print("Is xyz200")
    default: print("Not known")
}

Let Values

A case block can capture values in a tuple switch. We use the “let” keyword and provide an identifier.

Output is Monkey has size 200 for the example below.

Swift that uses let, value switch

let value = ("monkey", 200)

// Use let to capture a variable in a tuple.
switch (value) {
    case ("monkey", let size): print("Monkey has size \(size)")
    default: break
}

Tuples With Any Value

With an underscore, we can match just parts of a tuple in a switch.

Output is Second value is 1 for the example below.

Swift that switches, matches any tuple value

let tuple = ("cat", 1, "penguin")

// Switch on tuple.
// ... Match second value of the tuple.
switch (tuple) {
    case (_, 1, _): print("Second value is 1")
    case (_, 2, _): print("Second value is 2")
    default: print("No case")
}

Reference


This is the end of post