Chapters

Hide chapters

Design Patterns by Tutorials

Third Edition · iOS 13 · Swift 5 · Xcode 11

21. Command Pattern
Written by Joshua Greene

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The command pattern is a behavioral pattern that encapsulates information to perform an action into a command object. It involves three types:

  1. The invoker stores and executes commands.
  2. The command encapsulates the action as an object.
  3. The receiver is the object that’s acted upon by the command.

Hence, this pattern allows you to model the concept of executing an action.

When should you use it?

Use this pattern whenever you want to create actions that can be executed on receivers at a later point in time. For example, you can create and store commands to be performed by a computer AI, and then execute these over time.

Playground example

Open AdvancedDesignPatterns.xcworkspace in the Starter directory, and then open the Command page.

What should you be careful about?

The command pattern can result in many command objects. Consequently, this can lead to code that’s harder to read and maintain. If you don’t need to perform actions later, you may be better off simply calling the receiver’s methods directly.

Tutorial project

You’ll build a game app called RayWenToe in this chapter. This is a variation on TicTacToe. Here are the rules:

Building your game

Open Finder and navigate to where you downloaded the resources for this chapter. Then, open starter\RayWenToe\RayWenToe.xcodeproj in Xcode.

Creating and storing command objects

Add a new Swift file called MoveCommand.swift to the GameManager group, which is a subgroup within the Controllers group, and replace its contents with the following:

Implementing move commands

Replace the contents of enqueueMoveCommand(at:) with the following:

Key points

You learned about the command pattern in this chapter. Here are its key points:

Where to go from here?

You created a fun variant of TicTacToe where players select their moves in advance. There’s still a lot of functionality and changes you can make to RayWenToe:

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now