-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Automatic trigger for objectWillChange publisher #6
Automatic trigger for objectWillChange publisher #6
Conversation
…lue` to respect the `behavior` property
By adding the public static subscript<T: ObservableObject>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value where T.ObjectWillChangePublisher == ObservableObjectPublisher we are in fact enforcing that the property wrapper can only be used within an The best solution would probably be to provide two implementation, one more specialised then the other, like so: public static subscript<T: AnyObject>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value {
get {
// Return the saved wrapped value
instance[keyPath: storageKeyPath].wrappedValue
}
set {
instance[keyPath: storageKeyPath].wrappedValue = newValue
}
}
public static subscript<T: ObservableObject>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value where T.ObjectWillChangePublisher == ObservableObjectPublisher {
get {
// Return the saved wrapped value
instance[keyPath: storageKeyPath].wrappedValue
}
set {
instance.objectWillChange.send()
instance[keyPath: storageKeyPath].wrappedValue = newValue
}
} However, that currently produces the error For now, we could fall back for a runtime check: public static subscript<T: AnyObject>(
_enclosingInstance instance: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value {
get {
// Return the saved wrapped value
instance[keyPath: storageKeyPath].wrappedValue
}
set {
if let instance = instance as? any ObservableObject,
let publisher = (instance.objectWillChange as any Publisher) as? ObservableObjectPublisher {
// Trigger the `ObjectWillChangePublisher`
publisher.send()
}
instance[keyPath: storageKeyPath].wrappedValue = newValue
}
} |
…vableObject` types
Hey thanks for contributing! I was looking into adding something like this so users don't have to keep adding a I'll take a closer look tomorrow when I have some time. |
Hey looks good. Going to force merge this as there's a permission issue with the GitHub actions. |
Automatically triggers the
objectWillChange
publisher inCombine
sObservableObject
.Heavily inspired by John Sundell and the
@propertyWrapper
Swift Evolution Proposal.fixes #5