Enums with Static Subscripts Explained in Swift
This post assumes that you understand Swift subscripts and the difference between instance and static methods. If not, I suggest reading the following articles before continuing.
Static Subscript in an Enum
enum Days: CaseIterable {
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
case sunday
static subscript(index: Int) -> Days {
Days.allCases[index]
}
}
let day = Days[3]
print(day) // thursday
In this code, the Days enum conforms to the CaseIterable protocol. Inside Days, there are seven cases representing the seven days of the week.
Then a static subscript is declared with a parameter named index, that is of type Int.
By marking it as static, this subscript operates on Days itself — not on an instance of Days.
It maps an integer index to a specific Days case.
The implementation uses Days.allCases[index] to access the case at the given index in the allCases array.
Lastly, the static subscript is called with an index of 3.
Inside the subscript, Days.allCases[3] retrieves the fourth element (0-based indexing) from the allCases array.
Since the cases were defined in order, Days.allCases[3] corresponds to .thursday.
The day variable is assigned the .thursday case and then printed.
Note: By default a subscript is mutating, so there’s no need to explicitly mark it as such.