Swift 3.0闭包表达式:如果可变参数不在参数列表的最后,该怎么办? [英] Swift 3.0 closure expression: what if the variadic parameters not at the last place in the parameters list?

查看:78
本文介绍了Swift 3.0闭包表达式:如果可变参数不在参数列表的最后,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在闭包表达式参数列表中的某些其他参数之前,有一种技巧性的,间接的方法来使用可变参数,哈哈

There is a tricky, indirect way to use variadic parameters before some other parameters in closure expression parameters list, haha

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

我在bugs.swift.org中发现了一些相关问题:
SR-2475
SR-494

And I found some related issues in bugs.swift.org: SR-2475 SR-494

根据 Swift 3.0文档,对于闭包表达式,如果您命名可变参数,则可以使用可变参数(请参见闭包表达语法部分) )。但是对于Swift 2.x,描述为如果您将可变参数命名为并将其放置在参数列表的最后,则可以使用可变参数,边框部分已在Swift 3.0文档中删除,这是否意味着可变参数可以是闭包表达式的参数,即使它不在最后?如果是这样,为什么下面的代码无法成功编译?

According to the document of Swift 3.0, for a closure expression, "variadic parameters can be used if you name the variadic parameter"(see Closure Expresssion Syntax part). But for Swift 2.x, the description is "Variadic parameters can be used if you name the variadic parameter and place it last in the parameter list", the border part has been removed in Swift 3.0 document, is it means variadic parameter can be a argument of closure expression even it is not at the last place? If so, why the codes below can't compile successfully?

let testClosure = { (scores: Int..., name: String) -> String in
    return "Happy"
}
let k = testClosure(1, 2, 3, "John") // Missing argument for parameter #2 in call

如果可以在调用中使用参数标签,我认为编译器可以成功编译上面的代码,但是在Swift 3.0中,

If the argument label can be used in the call, I think the compiler can compile the code above successfully, but in Swift 3.0, closure expression's argument labels are regarded as Extraneous.

此外,Swift 3.0文档指出闭包表达式语法中的参数可以是输入输出参数,但Swift 3.0表示闭包表达式语法可以使用常量参数,变量参数和inout参数。为什么苹果要删除诸如常量参数,变量参数等描述,是因为在Swift 3.0中,参数不能为 var

Besides, Swift 3.0 document indicates that the parameters in closure expression syntax can be in-out parameters, but Swift 3.0 said that closure expression syntax can use constant parameters, variable parameters, and inout parameters. Why Apple removed descriptions like constant parameters, variable paramters, is it because in Swift 3.0, the parameters can't be var?

非常感谢您的帮助!

推荐答案

您可以在Swift 3.0中创建一个函数,其中可变参数参数不是最后一个参数。例如...

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)

我相信这是因为可变参数后面的参数被命名,所以func不会混淆下一个命名参数与更多可变参数。

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
}

这篇关于Swift 3.0闭包表达式:如果可变参数不在参数列表的最后,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆