cadence icon indicating copy to clipboard operation
cadence copied to clipboard

Get a list of all cases of an enum

Open SupunS opened this issue 1 year ago • 4 comments

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,
        )
    }
}

SupunS avatar Nov 04 '24 22:11 SupunS

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.

turbolent avatar Nov 04 '24 23:11 turbolent

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 avatar Nov 05 '24 05:11 bluesign

@bluesign Good idea! This could be an additional convenience feature of for loops 👍

turbolent avatar Nov 05 '24 20:11 turbolent

@supuns I would love to give this issue a try.

walterthesmart avatar Jul 09 '25 09:07 walterthesmart