据我所知,协议中不允许使用默认参数,这意味着以下内容无效:
protocol testProtocol {
func testFunc (_ a: String, _ b: String? = nil)
}
Run Code Online (Sandbox Code Playgroud)
所以我明白 b 仍然可以通过以下声明是可选的
protocol testProtocol {
func testFunc (_ a: String, _ b: String?)
}
Run Code Online (Sandbox Code Playgroud)
我的类可以符合这个协议:
class TestIt: testProtocol {
func testFunc(_ a: String, _ b: String?) {
print ("Do stuff with a and b")
}
}
Run Code Online (Sandbox Code Playgroud)
但是我想使用以下声明来调用此函数:
let test = TestIt()
test.testFunc("a")
Run Code Online (Sandbox Code Playgroud)
这不可避免地无法编译,解决方案似乎是
let test = TestIt()
test.testFunc("a", nil)
Run Code Online (Sandbox Code Playgroud)
然而,将 nil 传递给函数似乎并不是一种非常快捷的处理方式。
请注意,这是一个最小的示例,尚未准备好用于生产,只是为了确定协议中传递 nil 的一般问题的解决方案。
我可以在不使用 nil 的情况下调用 testFunc 吗?
小智 6
你可以这样做:
protocol TestProtocol {
func testFunc (_ a: String, _ b: String?)
}
extension TestProtocol {
func testFunc (_ a: String) {
self.testFunc(a, nil)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |