Swift 3.0 closure expression: what if the variadic parameters not at the last place in the parameters list?

对着背影说爱祢 提交于 2019-12-08 14:16:25

Still in Swift3 variadic arguments have to be the last parameter in the signature, because despite the fact that in your case the last parameter typed as String can be deduced, there's some cases where not, because of the infinite expansion of variadic argument:

let foo = { (i:Int..., j: Int) -> Int  in
    return j
}
foo(1,2)

...in Swift 3.0, the parameters can't be var?

var params where removed in Swift3 SE-0003 to avoid confusion with inout parameters, because both var and inout params can be assigned inside function, but just inout is reflected back.

 func doSomethingWithVar(var i: Int) {
    i = 2 // change visible inside function.
 }

 func doSomethingWithInout(inout i: Int) {
    i = 2 // change reflected back to caller.
 }

removing var from parameter list, remove the confusion above.

Variadic parameter have to be last and according to your situation, you can type this:

let testClosure = { (_ name: String, scores: Int...) -> String in
    return "Happy"
}
let k = testClosure("John", 1, 2, 3) 

You are able to create a func in Swift 3.0 where the variadic parameter is NOT the last argument. For example...

func addButtons(buttons: UIButton..., completion: (() -> ())? = nil)

I believe it's because the parameter following the variadic parameter is named, and so the func does not confuse the next named argument with more variadic arguments.

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