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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (3)

Write a response

Conforming to CaseIterable protocol can help!

--

Is there a way to make a generic version?

--