Memento Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memento Pattern runs in O(1) time and O(n) space, in Swift as in every other language.
- ✓Value semantics make the memento almost free: assigning a struct copies it, and the standard library collections are copy-on-write, so a snapshot costs a retain until someone mutates.
- ✓Make the state a struct with let properties and the memento is simply that struct; a Swift reviewer will not expect a separate type at all.
- ✓The Swift trap: The one way to lose value semantics is a struct that holds a class reference: the copy duplicates the reference, so the snapshot and the live object share that object and mutating it through either is visible in both.
- ✓Copy-on-write means a snapshot of a large array is a retain, so taking one is constant time; the copy happens on the first write afterwards.
What Memento Pattern actually is
Memento Pattern in Swift: what you actually reach for
Swift implementation
struct EditorState: Codable, Equatable {
var text: String = ""
var cursor: Int = 0
var marks: [Int] = []
}
final class Editor {
private var state = EditorState()
// Value semantics: this IS an independent snapshot. No clone needed.
func save() -> EditorState { state }
func restore(_ m: EditorState) { state = m }
func type(_ s: String) {
state.text += s
state.cursor += s.count
}
}
let ed = Editor()
let checkpoint = ed.save() // O(1): copy-on-write retains the buffers
ed.type("hello")
ed.restore(checkpoint)
// THE trap: a struct holding a CLASS shares that instance across copies.
final class Cursor { var offset = 0 }
struct Leaky { let cursor = Cursor() } // 'let' does not make this a value
var a = Leaky()
let snapshot = a // looks like a copy
a.cursor.offset = 9 // snapshot.cursor.offset is 9 tooThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Memento Pattern?
Value semantics make the memento almost free: assigning a struct copies it, and the standard library collections are copy-on-write, so a snapshot costs a retain until someone mutates. Codable gives serialisation for a persisted checkpoint with a one-line conformance, and PropertyListEncoder and JSONEncoder are the two built-in formats. NSKeyedArchiver exists on Apple platforms with secure coding, and UndoManager covers the undo case directly.
What is the most common Swift mistake when implementing Memento Pattern?
The one way to lose value semantics is a struct that holds a class reference: the copy duplicates the reference, so the snapshot and the live object share that object and mutating it through either is visible in both. Declaring the property let does not help, because it prevents reassignment rather than mutation of the referenced instance. The type still looks and behaves like a value type everywhere else, which is what makes it hard to spot; the fix is to make the nested type a struct as well, or to copy it explicitly at snapshot time.
How does Memento Pattern actually perform in Swift?
Copy-on-write means a snapshot of a large array is a retain, so taking one is constant time; the copy happens on the first write afterwards. That inverts the usual cost model and it has a sharp edge: mutating an array while a snapshot exists copies it on that first mutation, so a loop that mutates state while holding a snapshot per iteration copies the whole array every iteration. Taking the snapshot outside the loop, or releasing it before the mutation, restores the expected behaviour. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.