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
.
The solution to your problem is to pass the object that should run the selector method along with the selector to the initialisation of the ValueAnimator object. Also update the timerCallback() : @objc func timerCallback() { ... _ = target.
A selector is an identifier which represents the name of a method. It is not related to any specific class or method, and can be used to describe a method of any class, whether it is a class or instance method. Simply, a selector is like a key in a dictionary.
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled.
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
Use the Swift notion of optionals as:
if let result = object.notARealSelector?(/* args */) { // Use Result }
where the ? used following notARealSelector
with return false
to if
when there is no such method defined on the type of object
.
There is a caveat for optional protocol requirements:
Optional protocol requirements can only be specified if your protocol is marked with the @objc attribute. Even if you are not interoperating with Objective-C, you need to mark your protocols with the @objc attribute if you want to specify optional requirements.
But since your are asking about optional methods in the first place, you must be talking about this in the Objective-C context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With