Implementing Undo and Redo with the Command Design Pattern in Swift
Undo and redo are two common functions found in many apps and your users may expect it in your app as well. Whenever it’s possible to manipulate data, your users will be grateful when they can undo their errors. Imagine using Xcode without the possibility to undo your latest change or redo it again — it would be a horror!
This gif shows an example of how undo and redo work:
The three buttons “Red”, “Blue” and “Yellow” change the color of the view above. While the user changes the color, these changes are stored in a way, that they can be undone and redone again.
In this article we’ll take a detailed look at how to use Apples
UndoManager, a class facilitating undoing and redoing. It’s part of the Foundation Framework and provides a convenient way to implement this feature. To make thinks even easier, we’ll use the command design pattern to encapsulate actions as objects.
Representing a Command
Command represents an action that can be undone and redone. This allows to store an action in a traversable list. To support this, it contains two code blocks as properties:
execute to execute the action and
reverse to restore the state before executing the command.
Here is how
Command looks like:
In this example a
Command consists of these three properties:
isUndone: A boolean flag to determine whether the current command is already undone and thus can be redone.
execute: The action to execute the command. Used both at initial execution and when redoing a previously undone command.
reverse: Code block that’s executed to undo the command.
This is the bare minimum to create a history and support undo and redo. If you want to display more information to a user a
Command could have additional…