Swift Switch Statement

A Swift switch statement compares a value against one or more patterns and executes the code associated with the first matching case. It is useful when a program must choose between several possible paths.

Unlike switch statements in some other programming languages, a Swift switch must be exhaustive. Every possible value must be handled either by a specific case or by a default case.

In this tutorial, you will learn the Swift switch syntax, multiple-value cases, ranges, value binding, where conditions, tuples, fallthrough, and switch expressions with examples.

Swift Switch Statement Syntax

The syntax of a Swift switch statement is:

</>
Copy
switch expression {
    case value1 :
        statement(s)
        some more statement(s)
    case value2 :
        statement(s)

    /* some more case statements */
   
    default : /* Optional */
        statement(s)
}

In this syntax:

  • expression is evaluated once before the cases are checked.
  • value1, value2, and the other case labels represent values or patterns that can match the expression.
  • The statements under the first matching case are executed.
  • The default case handles values that are not matched by any earlier case.

A case may contain one or more statements. Swift does not automatically continue into the next case, so a break statement is normally unnecessary.

Note: The default block is optional only when the other cases cover every possible value of the switched expression. This requirement is known as exhaustiveness.

Basic Swift Switch Example

In this example, the expression a+b is evaluated and compared with the values in each case. The code belonging to the matching value is then executed.

main.swift

</>
Copy
var a=2
var b=3

switch a+b {
    case 4 :
        print("a+b is 4.")
        print("a+b is four.")
    case 5 :
        print("a+b is 5.")
        print("a+b is five.")
    case 6 :
        print("a+b is 6.")
        print("a+b is six.")
    default :
        print("no value has been matched for a+b.")
}

Output

a+b is 5.
a+b is five.

The expression evaluates to 5, so Swift executes the statements under case 5. It does not execute the following cases.

Swift Switch Without a Default Case

A switch can omit default when its cases cover all possible values. A Boolean value has only two possibilities, true and false, so both can be listed explicitly.

main.swift

</>
Copy
var a=true
var b=false

switch a&&b {
    case true :
        print("Hello User.")
    case false :
        print("Welcome User.")
}

Output

Welcome User.

The expression evaluates to false, so the case false block is executed. Because both Boolean values are covered, a default case is not required.

Match Multiple Values in One Swift Switch Case

Separate multiple values with commas when they should execute the same code. The case matches when the switched value equals any value in the list.

</>
Copy
let day = "Saturday"

switch day {
case "Saturday", "Sunday":
    print("Weekend")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    print("Weekday")
default:
    print("Invalid day")
}

Output

Weekend

This is clearer than repeating identical statements in separate cases.

Use Number Ranges in Swift Switch Cases

Swift switch cases support range patterns. A closed range such as 90...100 includes both endpoints, while a half-open range such as 0..<10 excludes its upper endpoint.

</>
Copy
let score = 84

switch score {
case 90...100:
    print("Grade A")
case 80...89:
    print("Grade B")
case 70...79:
    print("Grade C")
case 0...69:
    print("Needs improvement")
default:
    print("Invalid score")
}

Output

Grade B

The score 84 belongs to the range 80...89, so the second case runs.

Use Tuples with a Swift Switch Statement

A switch can match a tuple, allowing multiple related values to be tested together. Use an underscore as a wildcard when a tuple element can contain any value.

</>
Copy
let point = (0, 7)

switch point {
case (0, 0):
    print("The point is at the origin")
case (_, 0):
    print("The point is on the x-axis")
case (0, _):
    print("The point is on the y-axis")
case (-5...5, -5...5):
    print("The point is near the origin")
default:
    print("The point is outside the checked area")
}

Output

The point is on the y-axis

The pattern (0, _) matches because the x-coordinate is zero. The underscore accepts any y-coordinate.

Bind Matched Values with Case Let in Swift

Value binding captures part of a matched pattern in a temporary constant or variable. The captured value can then be used inside the case body.

</>
Copy
let point = (3, 0)

switch point {
case (let x, 0):
    print("The point is on the x-axis at \(x)")
case (0, let y):
    print("The point is on the y-axis at \(y)")
case let (x, y):
    print("The point is at (\(x), \(y))")
}

Output

The point is on the x-axis at 3

The first case binds the x-coordinate to x while requiring the y-coordinate to equal zero. The final case matches every remaining pair, which makes this switch exhaustive.

Add Where Conditions to Swift Switch Cases

A where clause adds a condition to a case pattern. The case executes only when both the pattern and the condition match.

</>
Copy
let point = (4, 4)

switch point {
case let (x, y) where x == y:
    print("The point is on the line x = y")
case let (x, y) where x == -y:
    print("The point is on the line x = -y")
case let (x, y):
    print("The point is at (\(x), \(y))")
}

Output

The point is on the line x = y

Swift Switch Fallthrough Behavior

Swift does not fall through from one case to the next by default. After a matching case finishes, execution continues after the entire switch statement.

Use the fallthrough keyword only when execution must continue into the next case body. The next case’s pattern is not tested again.

</>
Copy
let number = 5

switch number {
case 5:
    print("The number is five")
    fallthrough
case 1...10:
    print("The number is between one and ten")
default:
    print("The number is outside the range")
}

Output

The number is five
The number is between one and ten

Without fallthrough, only the first line would be printed.

Using Break in an Empty Swift Switch Case

Every switch case must contain at least one executable statement. Use break when a value should be recognized but no action is required.

</>
Copy
let character = "a"

switch character {
case "a":
    break
case "b":
    print("The character is b")
default:
    print("Another character")
}

print("Switch completed")

Output

Switch completed

Return a Value with a Swift Switch Expression

In current Swift versions, switch can be used as an expression that produces a value. Each case supplies the value assigned to the variable.

</>
Copy
let statusCode = 404

let message = switch statusCode {
case 200:
    "Success"
case 404:
    "Not Found"
case 500...599:
    "Server Error"
default:
    "Unknown Status"
}

print(message)

Output

Not Found

A switch expression is useful when each branch computes a value rather than performing a separate sequence of actions. Every case must produce a compatible result.

Swift Switch Statement Rules to Remember

  • A Swift switch must handle every possible value.
  • The first matching case is executed.
  • Cases do not fall through automatically.
  • Multiple matching values can be separated by commas.
  • Case labels can use values, ranges, tuples, wildcards, value binding, and where clauses.
  • Use break only when a case intentionally performs no action.
  • Use fallthrough carefully because the next case pattern is not checked.

Swift Switch Statement Frequently Asked Questions

Does Swift require a default case in every switch?

No. A default case is unnecessary when the listed cases already cover every possible value. For example, cases for both true and false completely cover a Boolean value.

Can one Swift switch case match multiple values?

Yes. Place the values in the same case and separate them with commas, such as case "Saturday", "Sunday":.

Does Swift switch need a break after each case?

No. Swift exits the switch after completing the matching case. A break statement is mainly used when a case must intentionally contain no other code.

What does case let mean in a Swift switch?

case let binds values from a matched pattern to temporary constants. These constants are available within that case’s statements.

What is the difference between fallthrough and multiple-value cases?

A multiple-value case groups several matching values under one code block. fallthrough executes the next case body after the current case, without testing whether the next pattern matches.

Swift Switch Tutorial Summary

In this Swift Tutorial, we learned how to use a switch statement with individual values, multiple conditions, ranges, tuples, value binding, where clauses, break, fallthrough, and switch expressions.