gpt4 book ai didi

swift - 使用默认参数值声明协议(protocol)函数

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:29 26 4
gpt4 key购买 nike

我希望这个函数在协议(protocol)中:

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

但是当我写这样的协议(protocol)时:

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

我遇到了一个错误:

Default argument not permitted in a protocol method

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

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

但是,我将无法调用缺少“完成”字的函数:

slideToRight(currentViewController viewController: vc)

最佳答案

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

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

关于swift - 使用默认参数值声明协议(protocol)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114966/

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