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]
CA1069: Enums should not have duplicate values.
To enable it, all you need to do is make your enum conform to the CaseIterable protocol and at compile time Swift will automatically generate an allCases property that is an array of all your enum's cases, in the order you defined them.
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
A type that provides a collection of all of its values.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With