Get a list of all cases of an enum
Issue to be solved
Just a nice to have feature.
Would be nice to be able to get a list of all supported cases of an enum as a list. That would be useful in-cases where one would need to perform some operation for-all cases of an enum.
e.g: was implementing a simple card-game, and wanted to initialize a deck-of-cards, where all possible symbols (♣, ♦, ♥, ♠) and all possible ranks/values are represented using two separate enums. Needed to iterate through all symbols and ranks - without having to hardcode the number of cases of each, and without having to use the enum-constructor, like:
for i in InclusiveRange<Int8>(0, 3) {
for j in InclusiveRange<Int8>(0, 12) {
let card <- create Card(
symbol: Symbol(rawValue: i)!,
rank: Rank(rawValue: j)!,
)
}
}
Suggested Solution
Above could have been simplified to something like below, if there was a method (say allCasses()) for enums to get all supported cases.
for symbol in Symbol.allCasses() {
for rank in Rank.allCasses() {
let card <- create Card(
symbol: symbol,
rank: rank,
)
}
}
That's a good idea!
Given that we need to keep backward-compatibility, and an existing Cadence program might define a case allCases (unlikely, but possible), we might have to require the author of the enum to opt into this feature.
For example, we could do this similar to how it is possible in Swift: conforming the enum to CaseIterable adds a nallCases property to the type.
This is very good idea, but I think this syntax looks better and more beginner friendly.
for symbol in Symbol
for rank in Rank {
let card <- create Card(
symbol: symbol,
rank: rank,
)
}
@bluesign Good idea! This could be an additional convenience feature of for loops 👍
@supuns I would love to give this issue a try.