Dir*_*nry 3 xcode swift protocol-extension
有没有办法将某些Swift函数标记为实现某些协议函数,以便在协议的签名发生更改时,编译器可以将实现标记为错误.
例如,考虑这个例子,我有一个实例Foo协议的默认实现UIViewController,我想覆盖它作为Bar子类的自定义类UIViewController.
// V1
protocol Foo {
func number() -> Int
}
extension Foo where Self: UIViewController {
func number() -> Int {
return 0
}
}
// Overrides the default implementation
extension Bar: Foo {
func number() -> Int {
return 1
}
}
Run Code Online (Sandbox Code Playgroud)
现在,该协议演变为:
// V2
protocol Foo {
func numberV2() -> Int
}
extension Foo where Self: UIViewController {
func numberV2() -> Int {
return 0
}
}
// I think I override the default implementation but not anymore.
// => error prone, no error from the compiler
extension Bar: Foo {
func number() -> Int {
return 1
}
}
Run Code Online (Sandbox Code Playgroud)
如何帮助我的Bar扩展程序知道该number功能不再与Foo协议相关?
不,目前(Swift 4.0)无法从编译器获得帮助以捕获这些"近乎未命中".不过,在swift-evolution邮件列表中已经出现过几次这个话题,所以人们肯定知道这是一个应该解决的问题.
事实上,Doug Gregor最近对Swift编译器进行了更改,该编译器能够捕获一些"接近未命中".此更改不是当前Swift版本的一部分,但将在Swift 4.1中.
当协议符合性时,"接近错过"警告会触发:
1)其中一个要求由"默认"定义(例如,来自协议扩展的定义)满足,并且
2)有一个相同的名义类型声明(或扩展声明)的成员声明符合性与要求同名并且不满足另一个要求.
当然,这些都是启发式方法,我们可以随着时间的推移调整启发式方法.
如果我理解正确,那么当前的启发式方法将无法捕捉到您的确切问题,因为它们只匹配具有完全相同名称(但不同类型)的方法,但正如Doug所说,未来可能会改进启发式方法.
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |