Last active
December 12, 2023 09:51
-
-
Save RuiAAPeres/27c592a08baf3b0b95e284de6dc3d54b 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
import Foundation | |
@propertyWrapper struct Notifier<Value> { | |
private let identifier: String | |
var wrappedValue: Value? { | |
didSet { | |
NotificationCenter.default.post(name: Notification.Name(identifier), object: wrappedValue) | |
} | |
} | |
init(identifier: String) { | |
self.identifier = identifier | |
} | |
} | |
@propertyWrapper class Notified<Value> { | |
private let identifier: String | |
var wrappedValue: Value? | |
init(identifier: String) { | |
self.identifier = identifier | |
NotificationCenter.default.addObserver(forName: Notification.Name(identifier), object: nil, queue: nil, using: {[weak self] notification in | |
self?.wrappedValue = notification.object as? Value | |
}) | |
} | |
} | |
struct Person { | |
@Notifier(identifier: "person.name.changed") | |
var name: String? | |
} | |
class Observer { | |
@Notified(identifier: "person.name.changed") | |
var name: String? | |
} | |
var person = Person() | |
var observer = Observer() | |
observer.name /// nil | |
person.name = "Hello world" | |
observer.name /// "Hello world" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you renaudjenny!