How to iterate over enum cases in Swift

You can iterate over all of the possible cases of an enumeration in Swift by making it conform to the CaseIterable protocol. When using CaseIterable, you can access a collection of all enum cases by using a allCases property and then iterate over it as an array. The order of allCases collection depends on the declaration order of enum cases.

Here is an example declaration of enumeration with String raw values which conforms to the CaseIterable protocol:

enum Frameworks: String, CaseIterable {
    case swiftui = "SwiftUI"
    case foundation = "Foundation"
    case uikit = "UIKit"
    case combine = "Combine"
}

Get the number of all possible enum cases:

let numOfCases = Frameworks.allCases.count

Iterate over all enum cases:

for framework in Frameworks.allCases {
    print(framework.rawValue)
}

Or using a forEach method:

Frameworks.allCases.forEach {
    print($0.rawValue)
}

Related tutorials: