Why is forwarding variadic parameters invalid?

霸气de小男生 提交于 2019-12-19 02:14:23

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24047706/why-is-forwarding-variadic-parameters-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!