Why is the transfer of variable parameters invalid?

Consider the parameter of the variational function:

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

Here foo can take several arguments, for example foo(5,4) . I'm interested in the Int... type and its supported operations. For example, why is this invalid?

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

Gives an error message:

Could not find overload for '_conversion', which accepts supplied arguments

Why is the transfer of variable parameters invalid?

What is the "conversion" that the compiler complains about?

+7
swift variadic-functions
source share
2 answers

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

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

Regarding the solution to this question: see my answer to this question .

+7
source share

You can redirect a variable argument, but the function you redirect must be defined using a parameter, which is an array, not a variable. So write your foo function as

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

and it works.

0
source share

All Articles