In Objective-C, you could call another function using its name, also known as a selector
. You did this through a syntax like this:
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:NO];
Swift doesn't have the concept of selector
s. You can pass a function directly into another function as a first-class value. But for older APIs that were built for Objective-C and take a selector
, Swift has the #selector
keyword. And since this is using the Objective-C runtime, you have to annotate your code with the @objc
attribute.
So the above ObjC example becomes this in Swift:
let timer = Timer.scheduledTimer(timeInterval: 2.0,
target: self,
selector: #selector(onTick),
userInfo: nil,
repeats: true)
In Swift, we don't use the concept of selectors. You can either pass your function directly as a parameter (since functions are first-class values in Swift), like so:
let timer = Timer.scheduledTimer(timeInterval: 2.0, repeats: false, block: onTick)
Or use a closure instead of passing a function:
let timer = Timer.scheduledTimer(timeInterval: 2.0, repeats: false) {
//...do something here
}
You will note, though, that the Swift version doesn't have a userInfo
parameter. If you need one, you would have to use the ObjC method. Also, if you are doing this in UIKit, a lot of which is still ObjC-based at its core, you will probably need to use the selector
version.
It's essentially a difference between a string-based API (selector
s are really just special strings behind the scenes) and a function-based API.