[英]Is a closure that is passed in as a parameter assigned to the parameter name in swift?
[英]Why Swift auto delete last closure parameter name?
例如:
private func test1(closure1: () -> Void, closure2: () -> Void) {
}
調用時:
self.test1(closure1: {
}) {
}
closure2
已被刪除。
還:
private func test2(closure1: () -> Void, closure2: () -> Void, closure3: () -> Void) {
}
調用時:
self.test2(closure1: {
}, closure2: {
}) {
}
closure3
已被刪除。
我不明白為什么蘋果設計成這樣。
它使代碼不那么清晰。
這只是行業中的一種慣例 - 將 function 中的最后一個閉包顯示為尾隨閉包。 里面只有語法糖,但值得一提的是,你可以用任何一種方式編寫它,我個人發現當方法具有多個閉包 arguments 時區分閉包很有用:
self.test1(closure1: {
...
}, closure2: {
...
})
這是(曾經)一個約定,讀起來就像您正在實現 function(或 object :):
Button("Press me") {
/* Do this block */
}
如您所見,調用 function 與實現類似。
(名稱)、(屬性)、(行為)。
更多信息在這里
從 Swift 5.3 開始,包括標簽:
Button("Press me")
action: { /* Do this block */ }
所以你也可以有多個尾隨閉包:
Button {
/* Do this block */
}
label: {
Image(systemName: "gear") // Custom button
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.