Swift Switch Statements

Use the switch statement with cases and the default and fallthrough keywords.
Switch. A variable has a value. In a switch statement, we test for all possible values. A switch must have a case for all possibilities.
Keywords. With the case keyword, we match a value or an interval. A let statement can introduce a temporary constant. With "where," we add checks.
A simple example. This program uses a simple switch statement. It assigns the constant "id" to 10. It then switches on that value.

Result: The "case 10" is reached and the program displays "Ten." The switch has a case for all possible values.

Default: This will match all values other than 9, 10 and 11 in the switch. In Swift, a case must match all possibilities.

Swift program that uses switch let id = 10 switch id { case 9: print("Nine") case 10: print("Ten") case 11: print("Eleven") default: break } Output Ten
Multiple case values. Sometimes a case should match multiple values. We cannot "stack" cases. Instead we must specify all possible values in one case.
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 } Output Medium
Ranges. A range is specified with a start, end and three periods in between. Ranges can be used in switch statements. All included values are matched by the range case.
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") } Output Upper half
Fallthrough. This keyword means that control proceeds to the next case in a switch. The next case is entered (even if the value does not match).

Note: This behavior is the default in some C-like languages. But in Swift it is specified with a special keyword.

Here: Case 2 is entered, but then case 1 and case 0 are entered because of the "fallthrough" statements.

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") } Output Number contains 2 Number contains 1 Number contains 0
String. In Swift we can use a string as the value being switched upon. We can use literals (like "cat") to match our string. The contents of the strings are compared.
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") } Output Is cat
Where. Sometimes we want further checking in a case. For example, we might want to check two variables (both parts of a tuple) at once. We use "where" for this.

Here: We call the test() method with tuple arguments. When the first item of a tuple is greater than or equal to 10, we print our values.

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")) Output Default Number = 15, Letter = b
Tuple. Here we switch on a tuple. We use a "tuple pattern" to match all items in the tuple. Many syntax features, like "let" and underscores, can be used to match parts of tuples.
Swift program 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") } Output Is xyz200
Let values. A case block can capture values in a tuple switch. We use the "let" keyword and provide an identifier (like "size" in this example).

Result: The first item in the tuple matches the value "monkey" and the size value is set to 200 from the tuple being switched upon.

Swift program 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 } Output Monkey has size 200
Tuples, any value. With an underscore, we can match just parts of a tuple in a switch. We specify the underscore to "ignore" items in a tuple case.

Here: We match only the second element in a 3-item tuple. The first and third items are ignored.

Swift program 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") } Output Second value is 1
Exhaustive, error. A switch cannot just match some cases. It must match all possible cases. The default block is useful for handling rare or unusual (unexpected) cases.
Swift program that causes switch error let height = 70 // This program will not work. // ... A switch must have a default clause. switch (height) { case 60: print(true) case 70: print(true) } Output /main.swift:8:1: Switch must be exhaustive, consider adding a default clause
At least one case, error. A switch cannot be empty. It must have at least one case or a default block. The Swift compiler will report an error on an empty switch.
Swift program that causes empty switch error let x = 5 // A switch cannot be empty. switch (x) { } Output /main.swift:5:1: 'switch' statement body must have at least one 'case' or 'default' block
Tuple pattern, error. For tuple patterns in a switch, each case must have the correct count of items. We cannot match a 2-item tuple with a 3-item tuple pattern case.
Swift program that causes tuple pattern error let result = (10, 20) // For a tuple switch, the pattern must be correct. switch (result) { case (10, 20, 30): print("OK") } Output /main.swift:3:6: Tuple pattern has the wrong length for tuple type '(Int, Int)'
A review. Switch is a powerful construct in Swift. It has unique features in this language. They are designed to make flow easier to design and control.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to