Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a typesafe way to use selectors in Swift?

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.

like image 664
Bill Avatar asked Jun 09 '14 14:06

Bill


People also ask

How do you call a selector in Swift?

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.

What is selector method?

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.

What is a selector Xcode?

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.


2 Answers

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

like image 168
Andrew Avatar answered Sep 21 '22 20:09

Andrew


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.

like image 45
GoZoner Avatar answered Sep 21 '22 20:09

GoZoner