Book Image

Swift by Example

By : Giordano Scalzo
Book Image

Swift by Example

By: Giordano Scalzo

Overview of this book

Table of Contents (15 chapters)

Implementing a deck of cards

So far, we have implemented a pretty generic app that lays out views inside a bigger view. Let's proceed to implement the foundation of the game—a deck of cards.

What we are expecting

Before implementing the classes for a deck of cards, we must define the behavior we are expecting, whereby we implement the calls in MemoryViewController, assuming that the Deck object already exists. First of all, we change the type in the definition of the property:

    private var deck: Deck!  

Then, we change the implementation of the start() function:

    private func start() {
        deck = createDeck(numCardsNeededDifficulty(difficulty))
    private func createDeck(numCards: Int) -> Deck {
        let fullDeck = Deck.full().shuffled()
        let halfDeck = fullDeck.deckOfNumberOfCards(numCards/2)
        return (halfDeck + halfDeck).shuffled()

We are saying that we want a deck to be able to return a shuffled version of itself...