Skip to content

Instantly share code, notes, and snippets.

Created May 21, 2016 23:14
Show Gist options
  • Save anonymous/01b4ddf1455ff9a6d5f01d2001562d1d to your computer and use it in GitHub Desktop.
Save anonymous/01b4ddf1455ff9a6d5f01d2001562d1d to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist May 21, 2016.
    17 changes: 17 additions & 0 deletions Card.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    enum Suit {}
    enum Rank: Int {}

    // In the example, let's say the Card is CustomStringConvertible so I can leverage all the external code
    // that prints stuff, and depends on using the var description
    struct Card : CustomStringConvertible {
    var rank: Rank
    var suit: Suit

    var description : String {
    return rank.simpleDescription() + suit.simpleDescription()
    }
    }

    // Define a protocol for specializing Arrays of Cards
    protocol _CardType {}
    extension Card: _CardType {}
    11 changes: 11 additions & 0 deletions Deck.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    typealias Deck = [Card]

    // Using swift's constrained extensions
    extension Array where Element : _CardType {

    // This is the method that would not compile if I try to use override
    // override var description: String {
    var description: String {
    return "Deck: " + self.map { "\($0)" }.joinWithSeparator(",")
    }
    }
    15 changes: 15 additions & 0 deletions DeckTests.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    class CardsTests: XCTestCase {

    var deck : Deck!

    override func setUp() {
    super.setUp()
    deck = Deck.standard() // Create a standard poker deck
    }

    func testBasicDeck() {
    // Here you get the error Ambiguous use of description
    print(deck.description)
    }

    }