2

Is there a native language feature for inline selectors in Swift? If not, is there an elegant pattern for this?

For example, an NSTimer using a Selector. This is a way you can do it without any inline function or block:

var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "update", userInfo: nil, repeats: false)

@objc func update() {
    print("timer up")
}

I would rather have something like this. This is a concept and does not compile.

var timer = NSTimer.scheduledTimerWithTimeInterval(2,
        target: self,
        selector: { println("timer up") }, // What can I do here?
        userInfo: nil,
        repeats: false)

This is similar to this question asked about inline selectors in Objective C.

Community
  • 1
  • 1
kev
  • 7,712
  • 11
  • 30
  • 41

1 Answers1

3

This code is bridged to Objective-C, and there's no way to do it there. The string you pass is ultimately converted to a selector (SEL) and passed to objc_msgSend. So, no.

You could take a look at BlocksKit, which adds these NSTimer methods, which would convert to closures in Swift.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287