How to use switch statement with enum in Swift

Swift language provides a switch statement which allows you to compare a given value against multiple possible matching options and perform respective action.

In its simplest form, a switch statement looks and works like that:

let frameworkName = “SwiftUI"

switch frameworkName {
case "UIKit":
    print("Using UIKit")
case "SwiftUI":
    print("Using SwiftUI")
    print("Framework undefined")

Given a variable, frameworkName, the switch statements attempts to find a matching case and performs appropriate action. In this case it prints “Using SwiftUI”. A switch statement in Swift has be exhaustive which means it has to cover all possible matching cases – that’s why we used a default case above, to cover all other possibilities.

Using switch statement with enums

Enumerations in Swift allow you to define a common type for a set of finite and related values.

Let’s define our first enum called Operator:

enum Operator: String {
    case addition = "+"
    case subtraction = "-"
    case multiplication = "*"
    case division = "/"

Because the set of defined values in enum is finite, it is very common to switch on the enum values instead of using multiple if else statements.

Here is an example matching Operator enum values with a switch statement in Swift:

let currentOperator: Operator = .subtraction

switch currentOperator {
case .addition:
    print("Performing addition")
case .subtraction:
    print("Performing subtraction")
case .multiplication:
    print("Performing multiplication")
case .division:
    print("Performing division")

The example code above prints “Performing subtraction”.

Related tutorials: