Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing number of parameters in a closure in Swift

Suppose I have a function:

func test(closure: (closureArgs: Double ...) -> Double){
    //some logic
}

Then later, I call it with:

test({$0 + $1 + $2 + $3})

Is it possible to get the number of closureArgs provided within test? The goal would be to do overloading. For example, test could include some code like:

func test(closure: (closureArgs: Double ...) -> Double){
    //somehow get access to number of arguments in closureArgs within the closure that was passed.
}

To clarify - I mean I need to access closureArgs's length INSIDE test but OUTSIDE closure

like image 970
wlingke Avatar asked Jan 13 '15 16:01

wlingke


1 Answers

Is it possible to get the number of closureArgs provided within test?

The Short Answer

No.

Slightly Longer Answer

No, it is not. Here's why:

The function is taking a closure as it's argument that by definition takes a variadic number of arguments. There's no possible way for someone calling the function to designate how many arguments the closure should take ahead of time. For example, if I were to call your function, it might look like this:

test() { (closureArgs: Double...) -> Double in
    var n: Double = 0
    for i in closureArgs {
        n += i
    }
    return n
}

As you'll notice, I don't define the number of arguments anywhere because the number of arguments is only specified when the closure is called. Then the number can be determined inside, or possibly returned.

Basically, the closure is called within test, so only you the caller know how many arguments it takes. Anyone consuming this function has no control over it.

like image 150
Logan Avatar answered Oct 13 '22 03:10

Logan