How do I implement undo/redo support?

Implementing undo/redo functionality in Swift can enhance user experience by allowing users to revert and reapply changes easily. This is commonly achieved using a stack-based model to track changes. Below is an example demonstrating how to implement undo and redo operations in a simple text editor app.

// Example of Undo/Redo implementation in Swift class UndoRedoManager { private var undoStack: [String] = [] private var redoStack: [String] = [] func performAction(_ action: String) { undoStack.append(action) redoStack.removeAll() // Clear redo stack on new action } func undo() -> String? { guard let lastAction = undoStack.popLast() else { return nil } redoStack.append(lastAction) return lastAction // The undone action can be returned or handled accordingly } func redo() -> String? { guard let lastRedoableAction = redoStack.popLast() else { return nil } undoStack.append(lastRedoableAction) return lastRedoableAction // The redone action can be returned or handled accordingly } } // Usage let editor = UndoRedoManager() editor.performAction("Type 'Hello'") editor.performAction("Type ' World'") print(editor.undo()) // Output: Type ' World' print(editor.redo()) // Output: Type ' World'

undo redo Swift user experience stack-based model text editor app