Search code examples
swiftsprite-kitselectorskaction

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


The docs say:

Declaration:

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

selector

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 perform(_:onTarget) 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.


Solution

  • 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:

    #selector(MyClass.myActionFunction(arg1:arg2:))
    

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

    let action = SKAction.run { [weak self] in
        self?.myActionFunction()
    }