[swift-evolution] [Pitch] Synthesized static enum property to iterate over cases

Logan Shire logan.shire at gmail.com
Fri Sep 8 04:55:04 CDT 2017

Googling ‘swift iterate over enum cases’ yields many results of various levels of hackery.
Obviously it’s trivial to write a computed property that returns an enum’s cases as an
array, but maintaining that is prone to error. If you add another case, you need to make sure
you update the array property. For enums without associated types,
I propose adding a synthesized static var, ‘cases', to the enum’s type. E.g.

enum Suit: String {
    case spades = "♠"
    case hearts = "♥"
    case diamonds = "♦"
    case clubs = "♣"

let values = (1…13).map { value in
    switch value {
    case 1: return “A”
    case 11: return “J”
    case 12: return “Q”
    case 13: return “K”
    default: return String(value)

let cards = values.flatMap { value in Suit.cases.map { “\($0)\(value)"  } }

Yields [“♠A”, “ ♥ A”, …, “♣K”]

- Logan Shire

More information about the swift-evolution mailing list