7

Consider the variadic function parameter:

func foo(bar:Int...) -> () { }

Here foo can accept multiple arguments, eg foo(5,4). I am curious about the type of Int... and its supported operations. For example, why is this invalid?

func foo2(bar2:Int...) -> () {
    foo(bar2);
}

Gives a error:

Could not find an overload for '_conversion' that accepts the supplied arguments

Why is forwarding variadic parameters invalid?

What is the "conversion" the compiler is complaining about?

Sam
  • 2,707
  • 1
  • 23
  • 32
yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • 4
    You'd think that, with the focus the language authors clearly had on righting [the wrongs of C](http://stackoverflow.com/questions/150543/forward-an-invocation-of-a-variadic-function-in-c), that they would have made this possible. – jscs Jun 04 '14 at 21:27
  • Reference: http://stackoverflow.com/questions/24024376/passing-an-array-to-a-function-with-variable-number-of-args-in-swift/24024428#24024428 – GoZoner Jun 04 '14 at 21:42

2 Answers2

7

When you call foo, the compiler expects a series of arguments, each of which must be an Int.

In the body of foo2, bar2 summarises all the passed arguments and actually has the type Int[] for all practical purposes. Thus, you cannot pass it directly to foo — as foo wants Int arguments, and not an Int[].

As for a solution to this: see my answer to this question.

Community
  • 1
  • 1
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
0

You can forward a variadic argument but the function you forward it to has to be defined with a parameter that is an array, not a variadic. So write your foo function as

func foo(bar:[Int]) -> () { }

and it works.

RobertL
  • 14,214
  • 11
  • 38
  • 44