【发布时间】:2020-01-13 02:56:32
【问题描述】:
我在提取示例的原始代码中的意图是让协议为许多抽象类提供一些默认实现,并根据需要在这些类下面的层次结构中进行覆盖。然而事情并没有按计划进行。
这是基本代码(取自游乐场,我将原始代码简化为问题的本质):
// protocol and default impls.
protocol MyProtocol {
func hello()
}
extension MyProtocol {
func hello() { print("hello from default in protocol extension") }
}
// Class hierarchy
class AbstractParent: MyProtocol {}
class Child: AbstractParent {
func hello() { print("hello from child") }
}
(Child() as MyProtocol).hello()
Child().hello()
运行这个我希望看到:
hello from child
hello from child
但是却得到了:
hello from default in protocol extension
hello from child
这对我来说很有意义,因为第一次调用是从 Child 转换为 MyProtocol 进行的,即使该函数存在于 Child 中,它也会调用协议函数,因为在编译时它只看到MYProtocol.
不过……
如果我将抽象父对象设置为包含这样的默认实现:
// protocol and default impls.
protocol MyProtocol {
func hello()
}
extension MyProtocol {
func hello() { print("hello from default in protocol extension") }
}
// Class hierarchy
class AbstractParent: MyProtocol {
func hello() { print("hello from abstract parent") }
}
class Child: AbstractParent {
override func hello() { print("hello from child") }
}
(Child() as MyProtocol).hello()
Child().hello()
我现在得到了预期的行为:
hello from child
hello from child
现在,尽管我们仍在转换为 MyProtocol,但它在 Child 中看到了实现。
谁能解释为什么向抽象父类添加一个实现会使这项工作有效?
【问题讨论】: