Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active July 30, 2018 09:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/ee0e3da7441d805fefbda72180187bdd to your computer and use it in GitHub Desktop.
Save ha1f/ee0e3da7441d805fefbda72180187bdd to your computer and use it in GitHub Desktop.
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