[英]Why can't i ignore a closure parameter with a default function in Swift?
I have a method with a closure as a parameter that defaults to a 'dummy' function if no closure is provided. 我有一个带有闭包的方法作为参数,如果没有提供闭包,则默认为“虚拟”功能。 However, whenever I try omitting the parameter with the default, the compiler throws the error: 但是,每当我尝试省略默认参数时,编译器都会引发错误:
Missing argument for parameter 'closureFuncWithDefault' in call 调用中缺少参数'closureFuncWithDefault'的参数
Insert 'parameterClosureFuncWithDefault: <#(object) -> Void#>' 插入'parameterClosureFuncWithDefault:<#(object)-> Void#>'
My code is as follows: 我的代码如下:
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)
}
})
}
Then from somewhere else: 然后从其他地方:
// some code
var objectThing = SCNReferenceNode (URL: ..... )
//
// code block...
//
functionWithDefault (object: objectThing) // <-- This throws the error.
SCN class and such things are not the relevant things, rather, the proper way to have a closure parameter with a default and being able to use it. SCN类与此类事物无关,而是具有默认值并能够使用它的正确方法。
The common syntax is to use an optional closure, calling it with ?
通用语法是使用可选的闭包,并使用?
调用?
: :
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)
}
}
}
Or, considering a simpler example: 或者,考虑一个更简单的示例:
func foo(completion: @escaping ((Bool) -> Void)? = nil) {
performAsynchronousTask { success in
completion?(success)
}
}
And then you can call this as either: 然后您可以将其称为:
foo()
Or 要么
foo { success in
if success { ... } else { ... }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.