如何在 Swift 中创建一个我可以选择调用的完成处理程序?
How to create a completion handler in Swift which I would call optionally?
目前,我有一个完成处理程序:
open func Start(completion: (() -> Void)) { ... }
但在这种情况下,我必须始终调用 completion
。
我怎样才能做一个可选的,所以在某些方法中我会使用 completion
块,但在其他方法中我会跳过它们而不添加到我的方法调用中?
例如,我想要的是:
self.present(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
我试过了
open func Start(completion: (() -> Void)? = nil) { ... }
添加问号,但在这种情况下我必须调用一个可选的完成块
completion?()
而且我不能简单地调用
start()
在完成块中我不需要的地方。它需要我调用它
您可以将其设为默认值为 nil
的可选参数:
open func Start(completion: (() -> Void)! = nil) {
guard completion != nil else {
return
}
completion()
}
其他一些方法:
func foo() {
Start()
Start(completion: nil)
Start(completion: {
// some code
})
Start {
// some code
}
}
您可以使用 nil
以外的默认值,例如什么都不做的块
open func start(completion: @escaping (() -> Void) = {}) {
}
但是,我看不出你调用 completion?()
有什么问题。
目前,我有一个完成处理程序:
open func Start(completion: (() -> Void)) { ... }
但在这种情况下,我必须始终调用 completion
。
我怎样才能做一个可选的,所以在某些方法中我会使用 completion
块,但在其他方法中我会跳过它们而不添加到我的方法调用中?
例如,我想要的是:
self.present(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
我试过了
open func Start(completion: (() -> Void)? = nil) { ... }
添加问号,但在这种情况下我必须调用一个可选的完成块
completion?()
而且我不能简单地调用
start()
在完成块中我不需要的地方。它需要我调用它
您可以将其设为默认值为 nil
的可选参数:
open func Start(completion: (() -> Void)! = nil) {
guard completion != nil else {
return
}
completion()
}
其他一些方法:
func foo() {
Start()
Start(completion: nil)
Start(completion: {
// some code
})
Start {
// some code
}
}
您可以使用 nil
以外的默认值,例如什么都不做的块
open func start(completion: @escaping (() -> Void) = {}) {
}
但是,我看不出你调用 completion?()
有什么问题。