Rom*_*ich 5 callback optional swift completion swift-protocols
我希望此功能在协议中:
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil) {
// do some stuff
}
Run Code Online (Sandbox Code Playgroud)
但是当我写这样的协议时:
protocol SomeDelegate {
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil)
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
协议方法中不允许使用默认参数
我知道,我可以这样定义签名:
protocol SomeDelegate {
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())?)
}
Run Code Online (Sandbox Code Playgroud)
但是然后,我将无法调用缺少“ completion”字样的函数:
slideToRight(currentViewController viewController: vc)
Run Code Online (Sandbox Code Playgroud)
不幸的是,协议中不允许使用可选参数,但是您可以通过创建协议扩展来解决此问题:
protocol SomeDelegate {
// with the completion parameter
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())?)
}
extension SomeDelegate {
// without the completion parameter
func slideToRight(currentViewController viewController: UIViewController) {
slideToRight(slideToRight(currentViewController: viewController, completion: nil))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2070 次 |
| 最近记录: |