使用默认参数值声明协议功能

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)

Swe*_*per 6

不幸的是,协议中不允许使用可选参数,但是您可以通过创建协议扩展来解决此问题:

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)

  • @LeoDabus是的,但是当您在协议类型上调用方法时,仍然必须添加参数。我认为这是OP试图避免的事情。 (3认同)
  • @LeoDabus那种失去协议的意义不是吗?在这种情况下,您不必强制实现方法。 (2认同)