Swift中的可选闭包4
我需要一个按需执行的闭包方法。Swift中的可选闭包4
在斯威夫特3我以前做这样的事情:
// Declare closure
var checksPerformed: ((Void) -> Void)? // Declaration
// Call when needed
checksPerformed?()
//Only executes when checksPerformed is called
checksPerformed = { _ in
// do stuff here
}
在斯威夫特4这不再是这种情况。
和固定这样的警告后没有像以前一样工作。 这样做的新方法是什么?
如果我更新声明:var checksPerformed: (() ->())?
我越来越
Distinguish between single-tuple and multiple-argument function types
// Declare closure
var checksPerformed: (() ->())? // Declaration
// Call when needed
checksPerformed?()
//Only executes when checksPerformed is called
checksPerformed = {
// do stuff here
}
使用
var checksPerformed: (()->(Void))?
如果你这样做,一切都应该按预期工作。
不要分配关闭时使用_在:
//Only executes when checksPerformed is called
checksPerformed = {
// do stuff here
}
//Call when needed
checksPerformed?()
在最后一段我说过我做过。它没有工作。我会更新我的原始邮件以包含错误。我不能做到这一点:''var checksPerformed:() - >(Void)?''。 “类没有初始化器”被抛出 – kernelpanic
你必须这样做(() - >(Void))?这将其声明为可选闭包;对不起,在我的组织答案?是问题句子的一部分。 – HixField
更新了答案,使其更加清晰 – HixField
就更新为:'VAR checksPerformed:(() - >无效)'或'VAR checksPerformed :(() - >())?'无论哪种方式都很好。我个人避免使用'Void',而不是在适当的地方使用'()'。 – oyalhi
var'checksPerformed:(() - >())?'//声明 –
@oyalhi我更新了问题 – kernelpanic