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 a straightforward task to complete the game. First of all, we add the instance variables to hold the number of the pairs already created, 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 apply the logic when a card is selected:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if selectedIndexes.count == 2 || selectedIndexes .contains(indexPath) { return } selectedIndexes.append(indexPath) let cell = collectionView.cellForItemAtIndexPath(indexPath) ...

Get Swift: Developing iOS Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.