31

Is there a way to get all values of an enum in an array?

Let's say I have the following code:

enum Suit {
    case Spades, Hearts, Diamonds, Clubs
}

Is there a method to get the following array?

[Spades, Hearts, Diamonds, Clubs]
Raspa
  • 311
  • 1
  • 3
  • 4

1 Answers1

6

I don't know if there is a method to do that. It's a really good question, hope someone will find another way much generic that mine. Anyways, I've done something that do the trick:

Here the enum:

// SuitCount is the last one, so the total of elements (used) is SuitCount-1
enum Suit: Int {
    case Spades, Hearts, Diamonds, Clubs, SuitCount
}

The function that return the values:

func getValueFromSuitAtIndex(#indexOfElement: Int) -> String {

     var value = ""

     switch indexOfElement {
     case 0:
        value = "Spades"
     case 1:
        value = "Hearts"
     case 2:
        value = "Diamonds"
     case 3:
        value = "Clubs"
     default:
        value = ""
     }   

     return value
}

And in another function, where ever you want:

var suitElements = String[]()
for index in 0...Suit.SuitCount.toRaw()-1 {
    suitElements.append(self.getValueFromSuitAtIndex(indexOfElement: index))
}
// suitElements printed is: [Spades, Hearts, Diamonds, Clubs]
println(suitElements)

Not really sure it's what you want, but hope that helps a bit.

EDIT 1:

An other solution, better: https://stackoverflow.com/a/24137319/2061450

Community
  • 1
  • 1
Lapinou
  • 1,467
  • 2
  • 20
  • 39