[swift-evolution] Native Observer for Swift
Mohamed Ebrahim Afifi
mohamede1945 at gmail.com
Tue Dec 22 05:16:28 CST 2015
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
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151222/9714eba4/attachment.html>
More information about the swift-evolution
mailing list