Implementing Undo and Redo with the Command Design Pattern in Swift

Using UndoManager to create an Undoable History

David Piper
6 min readMay 24, 2021

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

A 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…

--

--