How to Iterate Swift Enum String with example

An enum is a group of case statements with fixed values.

This tutorial explains the How to enumerate or iterate Enum String in SWIFT

Let’s declare an Enum class with a type of String

enum WEEKEND: String {
    case SUNDAY = "sunday"
    case SATURDAY = "saturday"
}

How to iterate through all enums?

Enum contains constants, declared with CaseIterable protocal. It contains allCases method that returns an sequence of Enum constants. You iterate using either for in loop or map method. If enum contains simple constains, It returns Enum constants. If it contains Type such as String or Int, you can use rawValue for each Constant.

Swift Enum iteration example

Swift provides CaseIterable protocol. add CaseIterable to enum declaration, It provides an allCases function that returns a sequence of collection of enum type constants.

Next, Use for in loop on sequence with each key, call key.rawValue to return the string assigned to constants.

Order of Enum strings are based on Enum declaration.

import Foundation
enum WEEKEND: String,CaseIterable {
    case SUNDAY = "sunday"
    case SATURDAY = "saturday"
}

for key in WEEKEND.allCases {
    print(key.rawValue)
}