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

Jonathan Hull jhull at gbis.com
Fri Sep 8 05:40:07 CDT 2017


+1000

I once made a country code enum, and creating that array was simple, but took forever, and was prone to mistakes.

Thanks,
Jon

> On Sep 8, 2017, at 2:56 AM, Logan Shire via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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”]
> Thoughts?
> 
> 
> Thanks!
> - Logan Shire
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list