Looping through enum values in Swift [duplicate]
Is there another way? Sure. Is it better, that's for you to decide:
func generateDeck() -> Card[]{ let ranksPerSuit = 13 var deck = Card[]() for index in 0..52 { let suit = Suit.fromRaw(index / ranksPerSuit) let rank = Rank.fromRaw(index % ranksPerSuit + 1) let card = Card(rank: rank!, suit: suit!) deck.append(card) } return deck}let deck = generateDeck()for card : Card in deck { println("\(card.description)") }
To use this, you will need to make sure that Rank
and Suit
enums both use Int
for their type definitions (ex: enum Rank : Int
).
Rank.Ace
should equal 1
and the first Suit
case should equal 0
.
If you want to loop similar to your existing code, you should still make your enums Int
types so you can use Rank.King.toRaw()
and the like.
The Apple documentation states that enums are not restricted to being 'simply integer values', but certainly can be if you desire them to be.
UPDATE
Idea taken from comment by @jay-imerman, and applicable to Swift 5
extension Rank: CaseIterable {}extension Suit: CaseIterable {}func generateDeck() -> [Card] { var deck = [Card](); Rank.allCases.forEach { let rank = $0 Suit.allCases.forEach { let suit = $0 deck.append(Card(rank: rank, suit: suit)) } } return deck;}