Start learning free

LESSON 70 OF 71 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Swift: A Two-Player Game Class

Practice Read the full explanation

Build a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game: it remembers the board and whose turn it is, lets the players take turns, and tells who has won.

The board: rows and columns are numbered 0, 1 and 2. Cell (0, 0) is the top-left corner, (0, 2) the top-right, (2, 0) the bottom-left and (2, 2) the bottom-right. A cell holds "X", "O" or "." when it is still empty.

Build:

  • A new game. The class has two private properties, set up when the object is created: board, a 3 by 3 array of Character filled with ".", and player: Character = "X". Every row must be its own array. All nine cells are empty and X moves first.
  • func move(_ row: Int, _ column: Int) plays one turn at the given row and column (always between 0 and 2, so you do not need to check the range).
    • If the cell is not empty, ignore the call: nothing changes and it is still the same player's turn.
    • Otherwise put the current player's mark in the cell, then give the turn to the other player (X becomes O, O becomes X).
  • func winner() -> Character returns the winner as a Character: "X", "O" or ".".
    • A player wins by having the same mark in all three cells of a row, a column, or one of the two diagonals ((0,0), (1,1), (2,2) and (0,2), (1,1), (2,0)). Three empty cells in a line are not a win.
    • If nobody has three in a row, return ".". That covers a game still in progress, an empty board and a draw.

You start with this code, which plays six games and prints the result of each one:

class Solution {
    func mainFunction() {
        var game = TicTacToe()
        game.move(0, 0)
        game.move(1, 0)
        game.move(0, 1)
        game.move(1, 1)
        game.move(0, 2)
        print("\(game.winner()) wins!")
        game = TicTacToe()
        game.move(0, 0)
        game.move(0, 1)
        game.move(0, 0)
        game.move(1, 0)
        game.move(1, 1)
        game.move(2, 2)
        game.move(2, 1)
        print("\(game.winner()) wins!")
        game = TicTacToe()
        game.move(0, 0)
        game.move(0, 1)
        game.move(1, 1)
        game.move(0, 2)
        game.move(2, 2)
        print("\(game.winner()) wins!")
        game = TicTacToe()
        game.move(0, 2)
        game.move(0, 0)
        game.move(1, 1)
        game.move(0, 1)
        game.move(2, 0)
        print("\(game.winner()) wins!")
        game = TicTacToe()
        game.move(0, 0)
        game.move(0, 1)
        game.move(0, 2)
        game.move(1, 1)
        game.move(1, 0)
        game.move(1, 2)
        game.move(2, 1)
        game.move(2, 0)
        game.move(2, 2)
        print("No winner: \(game.winner())")
        game = TicTacToe()
        print("No winner: \(game.winner())")
    }
}

Games played: X fills the top row; then a game where X tries to play on a cell that is already taken (ignored, and still X's turn) and O wins the middle column; X on the main diagonal; X on the other diagonal; a full board with no three in a row; and a brand-new game.

Expected output:

X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .

There are eight winning lines: three rows, three columns and two diagonals. A loop over i from 0 to 2 can check row i and column i together; the two diagonals come after the loop. Skip a line whose first cell is empty.

Check for a taken cell first and leave the move method before touching the board or the turn. Only a successful move passes the turn to the other player.

class TicTacToe {
    private var board = Array(repeating: Array(repeating: Character("."), count: 3), count: 3)
    private var player: Character = "X"

    func move(_ row: Int, _ column: Int) {
        if board[row][column] != "." { return }
        board[row][column] = player
        player = player == "X" ? "O" : "X"
    }

    func winner() -> Character {
        for index in 0..<3 {
            if board[index][0] != "." && board[index][0] == board[index][1] && board[index][1] == board[index][2] { return board[index][0] }
            if board[0][index] != "." && board[0][index] == board[1][index] && board[1][index] == board[2][index] { return board[0][index] }
        }
        if board[0][0] != "." && board[0][0] == board[1][1] && board[1][1] == board[2][2] { return board[0][0] }
        if board[0][2] != "." && board[0][2] == board[1][1] && board[1][1] == board[2][0] { return board[0][2] }
        return "."
    }
}

STEP 1 OF 14
    Ctrl + Enter to check

    SWIFT · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Swift, explained

    Problem overview

    The lesson asks for a TicTacToe class for players X and O on a 3 by 3 board. One object is one game. It remembers the board and whose turn it is, lets the players take turns, and reports the winner.

    Rows and columns are numbered 0 to 2, with cell (0, 0) at the top left and (2, 2) at the bottom right. A cell holds "X", "O" or "." when it is empty. The class has:

    • two private properties: board, a 3 by 3 array of Character filled with dots, and player: Character = "X", so X moves first;
    • move(_ row: Int, _ column: Int), which ignores a taken cell, and otherwise marks it and passes the turn;
    • winner() -> Character, which returns "X" or "O" for three in a row (a row, a column or either diagonal), and "." otherwise.

    The driver plays six games. In the first, X fills the top row. In the second, X tries to play on cell (0, 0) when it is already taken. That call is ignored and it is still X's turn, and in the end O wins the middle column. Then come the two diagonals, a full board with no line, and a fresh game. The expected output is:

    X wins!
    O wins!
    X wins!
    X wins!
    No winner: .
    No winner: .
    

    In the second game, X plays (0,0) and O plays (0,1). X's repeated (0,0) is ignored, so X then plays (1,0), O plays (1,1), X plays (2,2) and O plays (2,1). O now holds (0,1), (1,1) and (2,1), the middle column.

    Approach: store the grid, check eight lines

    The board is a nested array, so board[row][column] is one cell. A move is a small update to that grid. A win check is a search for three equal, non-empty marks along any of the eight winning lines: three rows, three columns and two diagonals.

    The check doesn't need to know who just moved. It looks at the whole board and returns whichever mark completes a line. Dots must be excluded: three empty cells in a line are equal to each other, but they aren't a win.

    Step by step

    1. Declare the class and write its closing brace at once. Each object is its own game with its own memory.
    2. Add the board as a private var: Array(repeating: Array(repeating: Character("."), count: 3), count: 3). The inner call builds a row of three dots, and the outer one repeats that row three times.
    3. Add player, a private Character starting as "X". Every new game starts with X to move.
    4. Start move, taking the row and the column, each 0, 1 or 2.
    5. Guard against a taken cell: if board[row][column] isn't a dot, leave with return before changing anything, so it stays the same player's turn.
    6. Place the mark: board[row][column] = player.
    7. Pass the turn with one conditional expression: if the player was "X" it becomes "O", otherwise "X".
    8. Start winner, returning a Character.
    9. Loop index over 0..<3. Each pass checks row index and column index together.
    10. Check the row: its first cell isn't a dot, and equals the second, which equals the third. If so, return that mark.
    11. Check the column the same way, with the two indexes swapped.
    12. After the loop, check the main diagonal: cells (0,0), (1,1) and (2,2).
    13. Check the other diagonal: (0,2), (1,1) and (2,0).
    14. Return ".". Reaching it means every check failed.

    The solution in Swift

    class TicTacToe {
        private var board = Array(repeating: Array(repeating: Character("."), count: 3), count: 3)
        private var player: Character = "X"
    
        func move(_ row: Int, _ column: Int) {
            if board[row][column] != "." { return }
            board[row][column] = player
            player = player == "X" ? "O" : "X"
        }
    
        func winner() -> Character {
            for index in 0..<3 {
                if board[index][0] != "." && board[index][0] == board[index][1] && board[index][1] == board[index][2] { return board[index][0] }
                if board[0][index] != "." && board[0][index] == board[1][index] && board[1][index] == board[2][index] { return board[0][index] }
            }
            if board[0][0] != "." && board[0][0] == board[1][1] && board[1][1] == board[2][2] { return board[0][0] }
            if board[0][2] != "." && board[0][2] == board[1][1] && board[1][1] == board[2][0] { return board[0][2] }
            return "."
        }
    }
    
    class Solution {
        func mainFunction() {
            var game = TicTacToe()
            game.move(0, 0)
            game.move(1, 0)
            game.move(0, 1)
            game.move(1, 1)
            game.move(0, 2)
            print("\(game.winner()) wins!")
            game = TicTacToe()
            game.move(0, 0)
            game.move(0, 1)
            game.move(0, 0)
            game.move(1, 0)
            game.move(1, 1)
            game.move(2, 2)
            game.move(2, 1)
            print("\(game.winner()) wins!")
            game = TicTacToe()
            game.move(0, 0)
            game.move(0, 1)
            game.move(1, 1)
            game.move(0, 2)
            game.move(2, 2)
            print("\(game.winner()) wins!")
            game = TicTacToe()
            game.move(0, 2)
            game.move(0, 0)
            game.move(1, 1)
            game.move(0, 1)
            game.move(2, 0)
            print("\(game.winner()) wins!")
            game = TicTacToe()
            game.move(0, 0)
            game.move(0, 1)
            game.move(0, 2)
            game.move(1, 1)
            game.move(1, 0)
            game.move(1, 2)
            game.move(2, 1)
            game.move(2, 0)
            game.move(2, 2)
            print("No winner: \(game.winner())")
            game = TicTacToe()
            print("No winner: \(game.winner())")
        }
    }
    

    Details worth knowing

    • Character versus String. The board holds Character values, and Swift won't compare a Character with a String: winner == s where s is a String fails with binary operator '==' cannot be applied to operands of type 'Character' and 'String'. A bare literal such as "X" adapts to Character where one is expected. That is why player == "X" and return "." both work.
    • Printing a Character. Interpolation shows the mark itself, so "\(game.winner()) wins!" prints X wins!, and a dot for no winner gives No winner: ..
    • Every row is its own array. Swift arrays are value types. When the outer Array(repeating:count:) repeats the row, each copy is independent. Setting board[0][0] = "X" changes only the top row.
    • Ternary for the turn. player = player == "X" ? "O" : "X" reads as: compare, then choose. The comparison binds tighter than the assignment, so it works as written.
    • The driver's var game. It is var because the driver assigns a new TicTacToe() to it for each game.

    Complexity

    The board has a fixed size, so each move and each winner call takes constant time: a move touches one cell, and the check looks at at most eight lines. The object stores nine cells and one mark, which is constant space.

    Edge cases and common mistakes

    • Forgetting the empty-cell test in winner. Without != ".", three empty cells in a row look like a line, and the method returns the dot straight away. A game where only row 1 is filled with X would then report no winner, because empty row 0 is checked first and returns early.
    • Moving on a taken cell. The guard must come before the mark is placed and before the turn changes. If the turn changed anyway, X's repeated move in the second game would hand the turn to O and everything after it would be wrong.
    • Passing the turn on every call. Only a successful move changes player.
    • Missing a diagonal. The loop covers rows and columns only. The two diagonals need their own checks after it.
    • Wrong anti-diagonal cells. The second diagonal is (0,2), (1,1), (2,0): the row goes up by one while the column goes down by one.
    • A full board with no line. The fifth game ends with all nine cells filled and nobody with three in a row, so winner() falls through to ".".
    • Playing after a win. This class doesn't stop moves after someone wins. It only reports the line it finds, which is fine for the lesson's tests.

    Testing

    These games, played on a fresh TicTacToe each time, give the lesson's results. Here is a diagonal win:

    var game = TicTacToe()
    game.move(0, 0)
    game.move(0, 1)
    game.move(1, 1)
    game.move(0, 2)
    game.move(2, 2)
    print("\(game.winner()) wins!")
    
    X wins!
    

    X holds (0,0), (1,1) and (2,2), the main diagonal, while O's marks at (0,1) and (0,2) don't make a line. A brand-new game gives No winner: ..

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free