enum Suit: String {
case spades = "♠"
case hearts = "♥"
case diamonds = "♦"
case clubs = "♣"
}
For example, how can I do something like:
for suit in Suit {
// do something with suit
print(suit.rawValue)
}
Resulting example:
♠
♥
♦
♣
You could iterate through an enum by implementing the
ForwardIndexType
protocol.The
ForwardIndexType
protocol requires you to define asuccessor()
function to step through the elements.Iterating over an open or closed range (
..<
or...
) will internally call thesuccessor()
function which allows you to write this:While dealing with
Swift 2.0
here is my suggestion:I have added the raw type to
Suit
enum
then:
Another solution:
I found myself doing
.allValues
alot throughout my code. I finally figured out a way to simply conform to anIteratable
protocol and have anrawValues()
method.The experiment was: EXPERIMENT
Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit.
So without modifying or enhancing the given code other than adding the method (and without using stuff that hasn't been taught yet), I came up with this solution:
The other solutions work but they all make assumptions of for example the number of possible ranks and suits, or what the first and last rank may be. True, the layout of a deck of cards probably isn't going to change much in the foreseeable future. In general, however, it's neater to write code which makes as little assumptions as possible. My solution:
I've added a raw type to the suit enum, so I can use Suit(rawValue:) to access the Suit cases:
Below the implementation of Card's createDeck() method. init(rawValue:) is a failable initializer and returns an optional. By unwrapping and checking it's value in both while statements, there's no need to assume the number of Rank or Suit cases:
Here is how to call the createDeck method: