[swift-evolution] Native Observer for Swift

Joe Groff jgroff at apple.com
Tue Dec 22 11:27:35 CST 2015


You should check out my proposal for property observers. You should be able to implement observation as a behavior with that feature.

-Joe

> On Dec 22, 2015, at 3:16 AM, Mohamed Ebrahim Afifi via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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.
> 
> // A native Swift class or struct
> class Foo {
> 
>     // property with any type
>     // We might have a keyword for declaring the property observable
>     /*@obserable*/ var bar: Int = 0
> }
> 
> let instance = Foo()
> 
> // anyone can subscribe to changes of the `bar` property.
> instance.bar += { newValue in
>     print(newValue)
> }
> 
> // you can store the return value to unsubscribe later.
> let observer = instance.bar += { newValue in
>     print(newValue)
> }
> 
> // unsubscribe
> instance.bar -= observer
> 
> // 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.
> 
> You can have a look at implementation for a similar library here https://github.com/slazyk/Observable-Swift <https://github.com/slazyk/Observable-Swift>
> 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.
> 
> 
> Best Regards,
> Mohamed Afifi
>  _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151222/d894a88f/attachment.html>


More information about the swift-evolution mailing list