Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values of an enum in swift [duplicate]

Tags:

swift

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] 
like image 338
Raspa Avatar asked Jun 04 '14 09:06

Raspa


People also ask

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

How do I get all enum cases?

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.

Can we inherit enum in Swift?

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.

What is CaseIterable in Swift?

A type that provides a collection of all of its values.


1 Answers

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

like image 64
Lapinou Avatar answered Sep 22 '22 13:09

Lapinou