Iterate over Swift enums

Derrick Ho
1 min readSep 10, 2017

Its not natively supported, so you’d have to create something on your own.

There are several solutions out there:

  1. Hacky Method
  2. Maintaining an Array of each case

And then there is my way, which is similar to Maintaining an array but I use a switch statement to guarantee that I did not miss a case. The compiler will tell me if a case is not handled by the switch

enum Planet: String {
case Mercury
case Venus
case Earth
case Mars
}
extension Planet {
static var array: [Planet] {
var a: [Planet] = []
switch Planet.Mercury {
case .Mercury: a.append(.Mercury); fallthrough
case .Venus: a.append(.Venus); fallthrough
case .Earth: a.append(.Earth); fallthrough
case .Mars: a.append(.Mars);
}
return a
}
}
Planet.array // [Mercury, Venus, Earth, Mars]

What I like about this solution is how it can be used for pretty much all kinds of enums. It uses a switch statement to guarantee that every case gets handled and it uses a fallthrough so that every case can get hit.

I suppose the only downside of this strategy is that you’d have to create this special method for every enum that wants this behavior.

--

--