Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Enumeration in Switch Statements in Swift
Written by Team Kodeco

In Swift, you can use enumerations in switch statements to match the different cases of the enumeration. This is a powerful feature that allows us to handle different cases of an enumeration in a clean and readable way. Here is an example of a switch statement that uses an enumeration of TrafficLight:

enum TrafficLight {
  case red, yellow, green
}

let trafficLight = TrafficLight.yellow

switch trafficLight {
case .red:
  print("Stop")
case .yellow:
  print("Caution")
case .green:
  print("Go")
}
// Output: "Caution"

You can also use the where clause to match specific conditions for certain cases. Here is an example of a switch statement that uses the where clause to match specific values of associated values:

enum Shape {
  case square(side: Double)
  case rectangle(width: Double, height: Double)
  case circle(radius: Double)
}

let shape = Shape.square(side: 2.0)

switch shape {
case .square(let side) where side > 2:
  print("Large square")
case .square(let side) where side <= 2:
  print("Small square")
case .rectangle(let width, let height):
  print("Rectangle with width \(width) and height \(height)")
case .circle(let radius):
  print("Circle with radius \(radius)")
default:
  print("Unexpected Shape")
}
// Output: Small square
© 2024 Kodeco Inc.