简体   繁体   中英

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.


Also:

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

}

when called:

self.test2(closure1: {

}, closure2: {

}) {

}

The closure3 had been deleted.


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 . 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:

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

Swift 5.2 and below

This is (was) a convention that reads like you are implementing a function (or an object:):

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

As you can see, calling the function is similar to implementing one.

(Name), (Attributes), (Behaviors).

More information here


Swift 5.3

Since Swift 5.3, labels are included:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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