简体   繁体   English

为什么 Swift 自动删除最后一个闭包参数名称?

[英]Why Swift auto delete last closure parameter name?

For example:例如:

private func test1(closure1: () -> Void, closure2: () -> Void) {

}

when called:调用时:

self.test1(closure1: {

}) {

}

The closure2 had been deleted. closure2已被删除。


Also:还:

private func test2(closure1: () -> Void, closure2: () -> Void, closure3: () -> Void) {

}

when called:调用时:

self.test2(closure1: {

}, closure2: {

}) {

}

The closure3 had been deleted. closure3已被删除。


I can't understand why apple design as this.我不明白为什么苹果设计成这样。

It's make code not so clear.它使代码不那么清晰。

That's just kind of convention in the industry - displaying last closure in a function as trailing closure .这只是行业中的一种惯例 - 将 function 中的最后一个闭包显示为尾随闭包 There is nothing but syntax sugar in it, however it's worth mentioning that you can write it either way, and i personally find it useful to distinguish closures when a method has multiple closure arguments:里面只有语法糖,但值得一提的是,你可以用任何一种方式编写它,我个人发现当方法具有多个闭包 arguments 时区分闭包很有用:

self.test1(closure1: {
    ...
}, closure2: {
    ...
})

Swift 5.2 and below Swift 5.2 及以下

This is (was) a convention that reads like you are implementing a function (or an object:):这是(曾经)一个约定,读起来就像您正在实现 function(或 object :):

Button("Press me") {
    /* Do this block */
}

As you can see, calling the function is similar to implementing one.如您所见,调用 function 与实现类似。

(Name), (Attributes), (Behaviors). (名称)、(属性)、(行为)。

More information here更多信息在这里


Swift 5.3 Swift 5.3

Since Swift 5.3, labels are included:从 Swift 5.3 开始,包括标签:

Button("Press me") 
action: { /* Do this block */ }

So you can have multiple trailing closures as well:所以你也可以有多个尾随闭包:

Button {
    /* Do this block */
}

label: {
    Image(systemName: "gear") // Custom button
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM