Enumerating enums in Swift
/How very interesting. Perhaps naively I expected if I defined the following enumeration
enum ProductCategory : String { case Washers = "washers", Dryers = "dryers", Toasters = "toasters" }
That I would be able to do something like
for category in ProductCategory{ //Do something for each category }
Nope... doesn't work. There's been some discussion in forums like StackOverflow (How to enumerate an enum with String type) that this requirement is bogus (an analogy being drawn with iterating over all integers), however I don't buy that at all. An enumeration is a sub-set of contextually valid values of some super type (Swift actually does something a bit cleverer than that, but I don't think it's pertinent here), and of course you may wish to iterate over all valid values in your context.
So why no default iterator? I think it comes down to the fact that an enumeration should be considered a set, and therefore Swift has no way of knowing what the correct order is. Alphabetic? Numerically high to low? Other languages might have left the behaviour undefined (you'll get the values in whatever order, don't depend on it), but that doesn't feel very Swift. So I think Apple have left us to define the order, if we want it.
This has led to me using the following pattern
enum ProductCategory : String { case Washers = "washers", Dryers = "dryers", Toasters = "toasters" static let allValues = [Washers, Dryers, Toasters] } for category in ProductCategory.allValues{ //Do something }
Here we are defining the order for enumeration, and I guess we could even provide multiple orders if we wanted to (perhaps even being responsive to the locale if the values were actually keys into localised strings and we then wanted to sort based on the locale for example).
There is a gotcha... how do we be certain that allValues does contain all the possible values? Sadly I can't see a way to do that, but a unit test that checked each value was stored in allValues would at least be a double check on yourself, if not a truly robust solution.
I'd love to hear other ideas on the topic, please do comment