Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Created December 8, 2022 15:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/10fbd5faa3d9f75b0d3d8c3e05943ea6 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/10fbd5faa3d9f75b0d3d8c3e05943ea6 to your computer and use it in GitHub Desktop.
/// 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