子类中的方法自定义未调用 [英] Method customization in sub class not called
问题描述
似乎,在协议扩展中具有默认实现的协议中定义为协议中的自定义点的函数,如果该基类最初没有自定义该函数,则无法在通过基类间接继承该协议的子类中自定义该函数.地方.
It seems that a function defined as a customization point in a protocol with a default implementation in protocol extension cannot be customized in a subclass that inherits the protocol indirectly via a base class if that base class did not customize the function at the first place.
这是一个简单的协议:
protocol MyProtocol
{
func myFunc() -> String
}
使用默认实现:
extension MyProtocol
{
func myFunc() -> String
{
return "hello from extension"
}
}
让我们创建一个基类和一个子类,如下所示:
Let's create a base class and a sub-class like this:
class BaseClass: MyProtocol
{
}
class SubClass: BaseClass
{
func myFunc() -> String
{
return "hello from SubClass"
}
}
BaseClass().myFunc() // "hello from extension"
(BaseClass() as MyProtocol).myFunc() // "hello from extension"
SubClass().myFunc() // "hello from SubClass"
(SubClass() as BaseClass).myFunc() // "hello from extension"
(SubClass() as MyProtocol).myFunc() // "hello from extension"
现在在基类中进行了自定义:
Now with a customization in the base class:
class BaseClass: MyProtocol
{
func myFunc() -> String
{
return "hello from BaseClass"
}
}
class SubClass: BaseClass
{
override func myFunc() -> String
{
return "hello from SubClass"
}
}
BaseClass().myFunc() // "hello from BaseClass"
(BaseClass() as MyProtocol).myFunc() // "hello from BaseClass"
SubClass().myFunc() // "hello from SubClass"
(SubClass() as BaseClass).myFunc() // "hello from SubClass"
(SubClass() as MyProtocol).myFunc() // "hello from SubClass"
这是预期的行为吗?
编辑11月14日:
关于本文的注释: http://nomothetis.svbtle来自 matt 的.com/the-ghost-of-swift-bugs-future 注释:
Note about about this article: http://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future from matt comment:
我认为这与我的问题并不严格相关,因为本文没有涉及子类间接继承协议的情况(这似乎有所不同).在后一种情况下,即使函数是自定义点(协议要求的一部分),对我来说也不是会发生静态调度.根据调用时推断的类型,行为会有所不同.
I think it is not strictly related to my question as the article does not cover the case where the subclass inherits the protocol indirectly (which seems to make a difference). In that later case, it is not obvious to me that a static dispatch does happen even if the function is a customization point (part of the protocol requirements). Depending on the inferred type at call time, behavior differs.
本文介绍了另一种情况,即该功能在扩展中具有默认实现,而不是协议要求的一部分,并且可能会掩盖子类的自定义.
The article covers the other case where the function has the default implementation in the extension while not part of the protocol requirements and may shadow subclass customizations.
编辑11月17日: