<div dir="ltr"><div><div>While willSet and didSet is a great property observers. They do work only on the declaration of the property. But for other objects to observe this, then they need to use KVO which is an Objective-C mechanism (We use String to subscribe, it doesn't offer generic capabilities for change). Besides, it's not portable.</div><div><br></div><div><div>// A native Swift class or struct</div><div>class Foo {</div><div><br></div><div> // property with any type</div><div> // We might have a keyword for declaring the property observable</div><div> /*@obserable*/ var bar: Int = 0</div><div>}</div><div><br></div><div>let instance = Foo()</div><div><br></div><div>// anyone can subscribe to changes of the `bar` property.</div><div>instance.bar += { newValue in</div><div> print(newValue)</div><div>}</div><div><br></div><div>// you can store the return value to unsubscribe later.</div><div>let observer = instance.bar += { newValue in</div><div> print(newValue)</div><div>}</div><div><br></div><div>// unsubscribe</div><div>instance.bar -= observer</div><div><br></div><div>// Also we can have a protocol to be implemented by any class/struct to give special events. For example Array would implement events for Insertion, Deletion, etc. Same for Dictionary and developers can do the same for their own classes.</div></div></div><div><br></div><div>You can have a look at implementation for a similar library here <a href="https://github.com/slazyk/Observable-Swift">https://github.com/slazyk/Observable-Swift</a></div><div>But as you can see there some issues like accessing the underlying value needs an operator which I believe with a native observer we will not have this issue.</div><div><br></div><div><br></div><div><div><div dir="ltr"><div><div dir="ltr">Best Regards,<div>Mohamed Afifi</div></div></div></div></div></div>
</div>