Skip to content

Memento ​

Memento captures enough state to restore an object later. Unlike Command, which stores an operation and its inverse, Memento stores a snapshot of state.

When it helps in iOS ​

A photo editor lets a user try crop and brightness changes, then cancel the edit. A snapshot allows one-step restore of the entire draft.

Original example: editing snapshot ​

swift
import Foundation
import CoreGraphics

struct EditSnapshot {
    fileprivate let crop: CGRect
    fileprivate let brightness: Double
}

final class PhotoEditSession {
    private(set) var crop = CGRect(x: 0, y: 0, width: 0, height: 0)
    private(set) var brightness = 0.0

    func setCrop(_ value: CGRect) { crop = value }
    func setBrightness(_ value: Double) { brightness = value }

    func snapshot() -> EditSnapshot {
        EditSnapshot(crop: crop, brightness: brightness)
    }

    func restore(_ snapshot: EditSnapshot) {
        crop = snapshot.crop
        brightness = snapshot.brightness
    }
}

let editor = PhotoEditSession()
let before = editor.snapshot()
editor.setBrightness(0.4)
editor.restore(before)

The session controls how its state is captured and restored. A screen can hold the snapshot while presenting a temporary editing flow.

Production decisions ​

Snapshot settings rather than full-resolution image buffers; image copies can be expensive. Persist a versioned snapshot if drafts must survive app termination. For long histories, use bounded checkpoints or commands to control memory. Restore on the correct actor if editor state drives UI.

A snapshot, not an inverse operation ​

PhotoEditSession owns crop and brightness and is the only type allowed to change them. snapshot() packages both values into an EditSnapshot; restore(_:) writes them back together. The screen can hold that snapshot while the user experiments and restore it on Cancel. It does not need to know how to reverse each individual slider movement, which is the main difference from Command-based undo.

From example to a photo editor ​

Take a snapshot when the edit sheet opens. Let controls mutate the draft session, previewing the image from draft settings. On Save, persist settings and discard the snapshot. On Cancel, restore the snapshot and dismiss. If edits can continue in another scene or survive app termination, persist a versioned settings snapshot with the document ID. Store crop coordinates in a defined coordinate space so a change in image size does not make restoration ambiguous.

Failure modes and verification ​

Test a snapshot before any edits, multiple edits followed by restore, and a save path that does not restore. Avoid snapshotting full image buffers for each slider movement; memory use can explode. For a multi-step undo history, use bounded snapshots or granular Commands. Keep snapshots opaque to callers so a later internal change does not force every screen to understand new fields.

All patterns

Released under the MIT License.