0

I use this code to perform actions with button tag:

func a() {
    print("a")
}

func b() {
    print("b")
}

let arrayOfActions: [()] = [a(),b()]

@objc func buttonAction(sender: UIButton!) {
    arrayOfActions[sender.tag-1]
}

But in this case the functions a() and b() are called. But I need only one function to be called.

4
  • Unrelated but the switch is pointless. The default case will never be executed and the code could even crash. Further the action syntax nowadays is @objc func buttonAction(_ sender: UIButton) Commented Jul 25, 2024 at 8:06
  • What is the output you get? I guess "a" or "b" are printed twice. It looks like the definition of arrayOfActions already calls the two functions. Commented Jul 25, 2024 at 8:07
  • This question is similar to: Array of functions in Swift. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 25, 2024 at 8:30
  • @vadian edited question with your comments Commented Jul 25, 2024 at 8:39

1 Answer 1

1

You're inserting function execution, rather than function as a variable, try this:

let arrayOfActions = [a, b] //<- remove `Void ()`

ArrayOfActions is a type of [() -> ()]

Updated: usage

@objc func buttonAction(sender: UIButton) {
    arrayOfActions[sender.tag - 1]() //<- notice `()` here, now you're calling its execution
}
Sign up to request clarification or add additional context in comments.

1 Comment

error in line - case sender.tag: arrayOfActions[sender.tag-1] - Function is unused

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.