我有一个方法,将闭包作为参数,默认为“假”'如果没有提供闭包,则起作用。但是,每当我尝试使用默认值省略参数时,编译器都会抛出错误:
缺少参数" closureFuncWithDefault'的参数在电话中 Insert' parameterClosureFuncWithDefault:<#(object) - >空隙#>'
我的代码如下:
func functionWithDefault (object: SCNReferenceNode = SCNReferenceNode(),
closureWithDefault: @escaping (_ object: SCNReferenceNode)->Void = { _ in return }) {
otherClassInstance.loadObject (object, loadedHandler: { [unowned self] loadedObject in DispatchQueue.main.async {
self.otherMethod (loadedObject)
closureWithDefault (virtualObject)
}
})
}
然后从其他地方:
// some code
var objectThing = SCNReferenceNode (URL: ..... )
//
// code block...
//
functionWithDefault (object: objectThing) // <-- This throws the error.
SCN类和这些东西不是相关的东西,而是使用默认值并能够使用它的闭包参数的正确方法。
答案 0 :(得分:0)
常见的语法是使用可选的闭包,用?
调用它:
func functionWithDefault (object: SCNReferenceNode = SCNReferenceNode(), closure: @escaping ((_ object: SCNReferenceNode) -> Void)? = nil) {
otherClassInstance.loadObject (object) { [unowned self] loadedObject in
DispatchQueue.main.async {
self.otherMethod (loadedObject)
closure?(virtualObject)
}
}
}
或者,考虑一个更简单的例子:
func foo(completion: @escaping ((Bool) -> Void)? = nil) {
performAsynchronousTask { success in
completion?(success)
}
}
然后您可以将其称为:
foo()
或
foo { success in
if success { ... } else { ... }
}