Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

No More Magic Selector Strings

Thursday — April 21st, 2016

If you've been fortunate enough to work in a Swift project you may have come across a situation where you need to talk to an Objective-C API that needs a selector. For example, scheduling an action with NSTimer.

In Objective-C you could easily set up a timer to repeat myAwesomeMethod every five seconds with something like:

[NSTimer scheduledTimerWithTimeInterval:5.0
    target:self
    selector:@selector(myAwesomeMethod:)
    userInfo:nil
    repeats:YES];

If you were in Swift 2.2 you could do the same thing via:

NSTimer.scheduledTimerWithTimeInterval(5.0, 
    target: self, 
    selector: Selector("myAwesomeMethod"), 
    userInfo: nil, 
    repeats: true)

But do you see that string? That ugly magic "myAwesomeMethod" string? You won't get autocomplete with that magic string. If you have a typo it will silently fail, which sucks. By that measure, it's more fragile than the Objective-C version.

Luckily, with Swift 3 this is going by the wayside. Swift will get the ability to use a #selector selector. In practice it would look something like:

NSTimer.scheduledTimerWithTimeInterval(5.0, 
    target: self, 
    selector: #selector(myAwesomeMethod:), 
    userInfo: nil, 
    repeats: true)

Which is much better. This will likely allow for autocomplete in Xcode for method names and the ability to know if there is a typo at compile time. This will be a breaking change but the Swift team has stated that they plan on including a migration tool to make the change painless.