Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Enumeration in Iteration in Swift
Written by Team Kodeco

In Swift, you can iterate over the cases of an enumeration using the allCases property. This property is automatically synthesized by the compiler for enumerations that don’t have associated values.

Here is an example of an enumeration of CompassDirection and how to iterate over its cases:

enum CompassDirection: CaseIterable {
  case north, south, east, west
}

for direction in CompassDirection.allCases {
  print(direction)
}

This will print the following output:

north
south
east
west
© 2024 Kodeco Inc.