Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get a list of all cases of an enum #3671

Open
Tracked by #3645
SupunS opened this issue Nov 4, 2024 · 3 comments
Open
Tracked by #3645

Get a list of all cases of an enum #3671

SupunS opened this issue Nov 4, 2024 · 3 comments
Labels
Feature Good First Issue Good for newcomers

Comments

@SupunS
Copy link
Member

SupunS commented Nov 4, 2024

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,
        )
    }
}
@turbolent
Copy link
Member

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.

@bluesign
Copy link
Contributor

bluesign commented Nov 5, 2024

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

@turbolent
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feature Good First Issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

3 participants