Objective-C Selectors in Swift

I was building new exercises in Swift—Apple’s new development language—for our upcoming iOS training class in San Francisco, and when combining Swift and Cocoa Touch, I discovered something really interesting.

In particular, for this tutorial, I will examine methods that require a selector as the argument, such as: performSelector:, respondsToSelector: or performSelector:withObject:afterDelay:.

For this example, I will create an NSTimer that will change the background color of a viewcontroller’s view every second. An NSTimer, just to refresh the concept, represents a timer object that waits until a certain time interval has elapsed and then fires, sending a specified message to a target object.

First, let’s write some code in Objective-C. If you are familiar with Objective-C, the following example won’t contain any secrets.

Begin by creating an iOS application using the Single-View template. Then, name the project Timer. Next, add a viewDidAppear: method in the ViewController.m and add the following code to the method:

The selector timerFireMethod: will look like this:

Simple, right? I simply created a timer that executes the timerFireMethod on the viewcontroller every second. This method prints out two values and changes the background color of the viewcontroller’s view to a random color.

Now, let’s demonstrate how to convert the above source code in Swift. First, use the Single-View template, again, to create a new Xcode project. Choose Swift as the main language and name the project SwiftTimer. Then, override the viewDidAppear function in the ViewController.swift file:

In order to be complete, here’s the timerFireMethod method translated in Swift:

Now, take a close look at line 1 in the viewDidAppear function of the Swift version. Notice that the function scheduledTimerWithTimeInterval on the NSTimer takes a Selector type as the third argument. The string you pass there as Selector represents the Objective-C version of the timerFireMethod: method.

In Objective-C, a selector is the name used to select a method to execute on an object, or, more succinctly, the unique identifier that replaces the name when the source code is compiled. A selector is represented by the special Objective-C type called SEL. The selector concept doesn’t exist in Swift. However, since Cocoa was originally developed in Objective-C, there are many methods using the SEL type as an argument. When you work with Swift and Cocoa Touch (or Cocoa), you need to use the Swift type Selector and pass it to the signature of the corresponding Objective-C method, not the Swift one.

This approach also works for the performSelector:, respondsToSelector:, performSelector:withObject:afterDelay: and other methods that are available in Cocoa Touch. You could also create a constant holding the selector type

and then pass it to method.

I hope this was useful and could save you some time.

Keep coding,




(Visited 700 times, 1 visits today)