1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
| // Base card rank
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
func equals(compare: Rank) -> Bool {
return self.rawValue == compare.rawValue
}
}
// Card suit
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
func color() -> String {
switch self {
case .hearts, .diamonds:
return "red"
case .spades, .clubs:
return "black"
}
}
}
// Poker struct with rank and suit.
struct Poker {
var rank: Rank
var suit: Suit
func description() -> String {
return "This card is a \(suit.color()) \(suit.simpleDescription()) \(rank.simpleDescription())."
}
}
var poker = [Poker]()
// Add cards
for i in 1...13 {
poker.append(Poker(rank: Rank(rawValue: i)!, suit: Suit.spades))
poker.append(Poker(rank: Rank(rawValue: i)!, suit: Suit.hearts))
poker.append(Poker(rank: Rank(rawValue: i)!, suit: Suit.diamonds))
poker.append(Poker(rank: Rank(rawValue: i)!, suit: Suit.clubs))
}
// Order by suit, then rank
poker.sort(by: {l, r -> Bool in
if l.suit.simpleDescription() < r.suit.simpleDescription() {
return false
} else if l.suit.simpleDescription().elementsEqual(r.suit.simpleDescription()) {
return l.rank.rawValue < r.rank.rawValue
} else {
return true
}
})
// Display
poker.forEach { (item) in
print(item.description())
}
|