声明带有默认参数值的协议函数。

21

我希望将这个函数定义在协议里:

func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil) {
    // do some stuff
}

但是当我编写这样的协议时:

protocol SomeDelegate { 
    func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil) 
}

我遇到了一个错误:

协议方法中不允许默认参数

我知道,我可以这样定义签名:

protocol SomeDelegate { 
    func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())?) 
}

但是,如果我不使用"completion"单词来调用缺失函数:

slideToRight(currentViewController viewController: vc)
1个回答

40

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

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))
    }
}

14
是的,但是当您在协议类型上调用该方法时,仍然需要添加参数。我认为这就是原帖作者试图避免的。 - Sweeper
4
那会失去这个协议的意义,不是吗?在那种情况下,您不必强制实现该方法。 - Sweeper
这与协议的要点无关,这是OP需要实现默认值的方式。顺便说一句,最好扩展UIViewController而不是将其作为参数传递。extension SomeDelegate where Self: UIViewController { func slideToRight(completion: ((Bool)->())? = nil) { } } - Leo Dabus
@LeoDabus,“???”的意思是什么?根据这里:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html,“在协议的定义中无法为方法参数指定默认值。” - Sweeper
谈论可选参数。顺便说一下,如果要设置除nil以外的默认值,则无需将参数定义为可选参数。 - Leo Dabus
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接