Created
June 3, 2014 14:21
-
-
Save nicnocquee/fb4bfd54e5cb455ed2c1 to your computer and use it in GitHub Desktop.
“Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/jp/jEUH0.l
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground - noun: a place where people can play | |
import UIKit | |
enum Rank: Int { | |
case Ace = 1 | |
case Two, Three, Four, Five, Six, Seven, Eigth, 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.toRaw()) | |
} | |
} | |
} | |
enum Suit: Int { | |
case Spades = 0 | |
case 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 .Spades: return "black" | |
case .Clubs: return "black" | |
case .Hearts: return "red" | |
case .Diamonds: return "red" | |
} | |
} | |
} | |
struct Card { | |
var rank: Rank | |
var suit: Suit | |
func simpleDescription() -> String { | |
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" | |
} | |
func fullDeckOfCards () -> Card[] { | |
var cards = Card[]() | |
for i in Suit.Spades.toRaw()...Suit.Clubs.toRaw() { | |
if let covertedSuit = Suit.fromRaw(i) { | |
let suit = covertedSuit | |
for j in Rank.Ace.toRaw()...Rank.King.toRaw() { | |
if let covertedRank = Rank.fromRaw(j) { | |
let rank = covertedRank | |
let card = Card(rank: rank, suit: suit) | |
cards += card | |
} | |
} | |
} | |
} | |
return cards | |
} | |
} | |
let aCard = Card(rank: .Three, suit: .Spades) | |
let cardDescription = aCard.simpleDescription() | |
let fullDeck = aCard.fullDeckOfCards() | |
for card in fullDeck { | |
let someCard = card.simpleDescription() | |
} | |
let card1 = fullDeck[0].simpleDescription() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I found a cleaner way.
Add this method into Suits.
And this into Card
What do you think? :)