Swift should directly support notifications
| Originator: | bigzaphod | ||
| Number: | rdar://17539879 | Date Originated: | July 2, 2014 |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | |
| Classification: | Reproducible: |
I think it’d be nice if Swift had a partially-bridged NSNotificationCenter ability built in. Then we could easily make type-safe observers that have nice function names and type-checked parameters rather than unpacking stuff from an NSNotification or rolling our own implementations that try to do something similar, but badly. I believe that C# has something like this which they call “delegates” and you declare individual methods in the class as being a delegate method, which can then be subscribed to externally. In Swift, I imagine something similar but with a different name such as:
class FancyThing {
notification somethingDidHappen(result:Int)
init() {
}
func doSomething() {
somethingDidHappen(result:42)
}
}
var thing = FancyThing()
thing.somethingDidHappen += (block or function reference or selector name?)
Notifications would always be functions and would always have a Void return type and they can always be directly called from within the class instance (or subclasses) without doing any optional checks even if there are no subscribers - but they could not be called from outside the class instance. So for example, this would not be allowed since attempts to send the notification from outside of the instance is probably unsafe and wrong anyway:
thing.somethingDidHappen(result:1000)
It’d also be rather cool if this could bridge to Objective-C and NSNotificationCenter automagically: So given the above example, the call to somethingDidHappen(result:42) in the doSomething() function would translate to a notification named FancyThingSomethingDidHappen with a userInfo value of @{“result” : @(42)} and appropriate object pointer being sent through the default notification center so that Objective-C code can observe the notifications easily in the usual ways.
I don’t think it would be necessary to bridge in the opposite direction, nor would this necessarily replace NSNotificationCenter in a Swift-only app - but it seems like the kind of thing that’d be very nice to have as I’m honestly not sure how to make notifications like these feel nice and clean and type safe and protocol-y in Swift without some first-class support. Perhaps there’s a way to do it using generics/meta stuff, but if it’s not straightforward then I don’t consider that a good sign.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!