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'
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?