ios

How to create array of function?


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.


Solution

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