Skip to content

Instantly share code, notes, and snippets.

@nicnocquee
Created June 3, 2014 14:21
Show Gist options
  • Save nicnocquee/fb4bfd54e5cb455ed2c1 to your computer and use it in GitHub Desktop.
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
// 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()
@kenlee
Copy link

kenlee commented Jun 4, 2014

I think I found a cleaner way.

Add this method into Suits.

func suits() -> Suit[] {
    return [Spades, Hearts, Diamonds, Clubs]
}

And this into Card

func fullDeck() -> Card[] {
    var deck = Card[]()
    for i in Rank.Ace.toRaw()...Rank.King.toRaw() {
        for s in suit.suits() {
            deck += (Card(rank: Rank.fromRaw(i)!, suit: s))
        }
    }
    return deck
}

What do you think? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment