Evan
Evan

Reputation: 2040

Have a selector return a value in Swift?

I was wondering if it's possible to make a selector return a value, and then set this value to some variable, if, for instance, a button is pressed.

Here's an example of what I mean:

let test = MyTapGesture(target: self, action: #selector(sampleFunction))
//somehow, here, I wanted the selector to return the value 5, and I can access it in this code
cell.button.addGestureRecognizer(test)

and the code for the selector would be something like this:

@objc sampleFunction() -> Int{
    //do some stuff that's important when the button is pressed
    return 5
}

Is this possible?

Thank you!

Upvotes: 0

Views: 744

Answers (1)

OOPer
OOPer

Reputation: 47886

General answer for Have a selector return a value in Swift?

Yes, a selector is just a key for a specific existing method, so if the method returns a value, you may get the returned value invoking the selector.

But, this does not mean you can return a value from an action method.

Specific answer for your case

No, action methods are invoked from inside iOS, and iOS ignores the returned value. (In some cases, calling a method with return value would make your app crash.)

If you need to set cell.button.tag = 5, you may need to write it in your sampleFunction explicitly:

    @objc func sampleFunction(_ gestureRecognizer: MyTapGesture) {
        let button = gestureRecognizer.view as! UIButton
        button.tag = 5
        //...
    }

Upvotes: 1

Related Questions