Skip to content

Instantly share code, notes, and snippets.

@swhitty
Last active January 29, 2024 07:01
Show Gist options
  • Save swhitty/bdfc75b02fb447279180496577aa7c07 to your computer and use it in GitHub Desktop.
Save swhitty/bdfc75b02fb447279180496577aa7c07 to your computer and use it in GitHub Desktop.
PropertyWrapper that can be applied to `Equatable` properties of `ObservableObject` to notify observers of unique changes.
/// PropertyWrapper that can be applied to `Equatable` properties of `ObservableObject` to notify observers of unique changes
@propertyWrapper
struct UniqueChanges<Element: Equatable> {
init(wrappedValue: Element) {
self._wrappedValue = wrappedValue
}
@available(*, unavailable, message: "@UniqueChanges can only be applied to types that conform to `ObservableObject`")
var wrappedValue: Element {
get { fatalError() }
set { fatalError() }
}
private var _wrappedValue: Element
// Classes get and set `wrappedValue` using this subscript.
static subscript<T: ObservableObject>(_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Element>,
storage storageKeyPath: ReferenceWritableKeyPath<T, UniqueChanges>) -> Element where T.ObjectWillChangePublisher == ObservableObjectPublisher {
get {
instance[keyPath: storageKeyPath]._wrappedValue
}
set {
guard instance[keyPath: storageKeyPath]._wrappedValue != newValue else { return }
instance.objectWillChange.send()
instance[keyPath: storageKeyPath]._wrappedValue = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment