For the most part, Swift is a huge improvement over Objective-C in terms of type safety. One glaring exception is selectors. In Objective-C, using the expression @selector(notARealSelector:)
will give a compiler warning. The Swift equivalent, Selector("notARealSelector:")
will always compile but will fail at runtime.
Is there a typesafe way to use selectors in Swift, so I can work with Objective-C APIs that require them?
I have a lot of NSNotification
observers in my app and would like to have some kind of compile-time checking that I'm not making typos in my selectors.
Edit: The specific use case is NSNotificationCenter.addObserver
.
Typesafe selectors were just released in Xcode 7.3 beta 4:
let sel = #selector(insertSubview(_:aboveSubview:)) // sel has type
Selector
is now a first class citizen and comes with some nice Swift compiler warnings. If needed you can still pass in a string:
let sel = Selector("propertyName")
See a much more complete answer here: @selector() in Swift?
Xcode Release Notes: http://adcdownload.apple.com/Developer_Tools/Xcode_7.3_beta_4/Xcode_7.3_beta_4_Release_Notes.pdf