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)

Finishing the game

In this section, we will finally be able to play the game.

Implementing the game logic

After having all the required functions in place, it's now straightforward to complete the game. First of all, we add the instance variables to hold the number of the pairs already made, the current score, and the list of selected cards turned up:

    private var selectedIndexes = Array<NSIndexPath>()
    private var numberOfPairs = 0
    private var score = 0

Then, we put the logic when a card is selected:

    func collectionView(collectionView: UICollectionView,
        didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if selectedIndexes.count == 2 ||
            contains(selectedIndexes, indexPath) {
        let cell = collectionView.cellForItemAtIndexPath(indexPath)
            as CardCell
        if selectedIndexes.count < 2 {