gpt4 book ai didi

swift - 如何在 Swift 中创建一个我可以选择调用的完成处理程序?

转载 作者:行者123 更新时间:2023-11-28 09:48:52 24 4
gpt4 key购买 nike

目前,我有一个完成处理程序:

open func Start(completion: (() -> Void)) { ... }

但在这种情况下,我必须始终调用完成。我怎样才能做一个可选的,所以在某些方法中我会使用 completion block ,但在其他方法中我会跳过它们而不添加到我的方法调用中?

例如,我想要的是:

self.present(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)

我试过了

open func Start(completion: (() -> Void)? = nil) { ... }

添加问号,但在这种情况下我必须调用一个可选的完成 block

completion?()

我不能简单地调用

start()

我不需要在完成 block 中的地方。它需要我调用它

最佳答案

您可以将其设为默认值为 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
}
}

关于swift - 如何在 Swift 中创建一个我可以选择调用的完成处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com