Last active
January 29, 2024 07:01
-
-
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.
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
/// 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