-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Swift 4 Programming Cookbook

From the last few recipes on collection types, we have seen, that their elements are accessed through subscripts. However, it's not just collection types that can have subscripts; your own custom types can provide subscript functionality too.
Let's create a simple game of tic-tac-toe, also known as Noughts and Crosses. To do this, we need a three-by-three grid of positions, with each position being filled by either a nought from Player 1, a cross from Player 2, or nothing. We can store these positions in an array of arrays.
The initial game setup code uses the constructs we covered earlier, so we won't go into its implementation. Enter the following code into a new playground so that we can see how subscripts can improve its usage:
enum GridPosition: String { case player1 = "o" case player2 = "x" case empty = " " } struct TicTacToe { var gridStorage: [[GridPosition]] = [] init() { gridStorage.append(Array(repeating...