Created
December 8, 2022 15:41
-
-
Save krzyzanowskim/10fbd5faa3d9f75b0d3d8c3e05943ea6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// This code defines an init method for the Binding type. This method accepts three parameters: | |
/// | |
/// An object of any type T | |
/// A key path to a property of type Value on that object | |
/// An optional UndoManager object | |
/// | |
/// The init method sets the Binding value to the value of the property specified by the key path. It also sets the set value of the Binding to a closure that updates the value of the property at the key path and registers an undo operation with the provided UndoManager, if one is given. | |
/// | |
/// This allows the Binding object to be used to access and update the value of the specified property on the provided object, and to register undo operations for those updates with the UndoManager. | |
extension Binding { | |
init<T>(_ object: T, _ keyPath: ReferenceWritableKeyPath<T, Value>, undoManager: UndoManager? = nil) { | |
self.init { | |
object[keyPath: keyPath] | |
} set: { newValue in | |
let originalValue = object[keyPath: keyPath] | |
object[keyPath: keyPath] = newValue | |
if let undoManager = undoManager { | |
undoManager.registerUndo(withTarget: undoManager, handler: { _ in | |
object[keyPath: keyPath] = originalValue | |
}) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment