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
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution