Confused Confused - 1 year ago 138
Swift Question

What is a selector in SKAction: perform(_:onTarget:)

The docs say:


class func perform(_ selector: Selector, onTarget target: Any) -> SKAction


The selector of the method to call.

I am uncertain what a selector of a method is. Hence the question.

It seems like it would be the name of the method/function, but creates (in me) uncertainty because it's never described as being this, so I kind of think it might be something else, something more profound, perhaps.

I'm presupposing
is a way for a part of code to be flexibly telling an object decided at runtime what action to perform. But am not entirely sure that I have its purpose right. That's the context within which I'm thinking about this.

Not only is my question different from the linked "similar" question in terms of context, it's also a different, and much more specific question: WHAT is a selector in this particular function.

Answer Source

A selector is the name of a function, and a target is an object on which to perform the function. You construct a selector using the syntax: #selector(<function name>), for example:

class MyClass {

    func createAction() {
        let action = SKAction.perform(#selector(MyClass.myActionFunction), onTarget: self)
        // ...

    @objc func myActionFunction() {
        // do stuff

To create a selector for a function that takes arguments, use the syntax:


You can also accomplish this same thing using a block instead of a selector:

let action = { [weak self] in
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download