How to use an array of functions in Swift

Viewed 141

I have read all the posts I can find here about arrays of functions - great you can do it. I figured. But none of the posts show practically how to use them (at least not what I'm trying to do). Here's what I want - they can all take the same args, but that's not a requirement.

This article is close, and will allow me to loop through to execute each function (which meets the first goal).
https://stackoverflow.com/a/24447484/11114752

But... what if I want to execute a single function by reference? In other words, how to call just the referenced Arity2 function - for example:

// None of these work (with or without the parameter labels)
funcs.Arity2(n: 2, S: "Fred)    // value of type [MyFuncs] has no member .Arity2
funcs[Arity2](n: 2, S: "Fred")  // no exact matches to call in subscript
funcs[.Arity2](n: 2, S: "Fred") // Cannot call value of non-function type...

let fn = funcs.first(where: { a whole ton of permutations here to try to match Arity2 }) -- a whole lotta frustrating nope...

Help, please! Nothing I've tried works. The pre-compiler just goes in circles making suggestions that don't pan out and it will not compile.

EDIT: The reason for the array in the first place is that I'm going to have a quite a few functions, and I don't know what they all are in advance. Essentially, I want a plugin type of architecture. Where I can add to the list of functions (ideally within an extension of the class, but that's another problem..) and not change the processing loop that executes each function in order.

2 Answers

I assume you need something like

    _ = funcs.first {
        if case let MyFuncs.Arity2(f) = $0 {
            f(2, "Fred")
            return true
        }
        return false
    }

It can be achieved in a much simpler way if you know the position of the function in the array.

Assuming you have:

func someFunc(n: Int, s: String) { 
    print("call \(n) \(s)")
}

var funcs = [MyFuncs.Arity2(someFunc)]

you can do:

if case .Arity2(let f) = funcs.first {
    f(2, "Fred")
}

By replacing funcs.first with funcs[i] you can access the i-th index (first make sure it does exist).

Related