[swift-evolution] Proposal: Expose getter/setters in the same way as regular methods

Charles Srstka cocoadev at charlessoft.com
Sun Dec 27 03:28:53 CST 2015

> On Dec 13, 2015, at 6:49 PM, Marc Knaup via swift-evolution <swift-evolution at swift.org> wrote:
> Also it's unlikely that all mutable properties will support observation automatically. That would require the optimizer to keep using dynamic dispatch for all of them which will hurt performance.

Not really. All that’s required for Objective-C KVO to work for a stored property is for the willChangeValueForKey() and didChangeValueForKey() methods to be called before and after the value is set. If you put those calls in willSet and didSet for a Swift stored property, you can get KVO compliance with no dynamic dispatch at all. The reason Objective-C typically requires dynamic dispatch for this is because KVO is purely a framework-level feature, and is not built into the library, so the framework code has to rewrite your class to add the needed methods. If you built a KVO-like system right into the language, the notification methods could be added right at compile time, and it’d work fine. Of course, if I were redesigning KVO, I’d probably eliminate willChangeValueForKey() and just include the old value as a parameter to didChangeValueForKey(), since if there’s only one method to call, you can set the property on a secondary thread, and then just call the observation method asynchronously on the main thread, which will avoid tying up the worker thread waiting for UI updates that result from the KVO update.

Of course, if you’re worried about the performance costs associated with that extra method call, you might want to include a keyword, such as “observable”, and only generate the method call(s) if that keyword is on the property. This would probably be a good thing *anyway*, since one of the weaknesses of the current KVO implementation is that there’s no way to know whether a property is KVO observable or not without reading the documentation for that method, since computed properties need to state their dependencies in order to property support KVO, and whether this has been done is not reflected in the interface at all.


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

More information about the swift-evolution mailing list