Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active Jul 30, 2018
Embed
What would you like to do?
class History<T> {
// MARK: Properties
private var _undoStack: [T] = []
private var _redoStack: [T] = []
private var _current: T
// MARK: Getter, Setter
var current: T {
get {
return _current
}
set {
_undoStack.append(current)
_current = newValue
_redoStack = []
}
}
var canUndo: Bool {
return !_undoStack.isEmpty
}
var canRedo: Bool {
return !_redoStack.isEmpty
}
// MARK: Initializers
init(state: T) {
self._current = state
}
// MARK: Functions
func undo() {
guard let nextState = _undoStack.popLast() else {
return
}
_redoStack.append(_current)
_current = nextState
}
func redo() {
guard let nextState = _redoStack.popLast() else {
return
}
_undoStack.append(_current)
_current = nextState
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment