我知道这个问题的标题令人困惑,但下面的例子解释了奇怪的行为:
protocol Protocol { func method() -> String } extension Protocol { func method() -> String { return "From Base" } } class SuperClass: Protocol { } class SubClass: SuperClass { func method() -> String { return "From Class2" } } let c1: Protocol = SuperClass() c1.method() // "From Base" let c2: Protocol = SubClass() c2.method() // "From Base"
为什么c1.method()和c2.method()返回相同的?为什么SubClass中的method()不起作用?
有趣的是,在没有声明c2的类型的情况下,这将起作用:
let c2 = SubClass() c2.method() // "From Class2"
解决方法
问题是c1和c2属于Protocol类型,因为你已经用这种方式明确定义了它们的类型(记住:协议是完全成熟的类型).这意味着,当调用method()时,Swift调用Protocol.method.
如果你定义类似的东西:
let c3 = SuperClass()
… c3属于SuperClass类型.由于SuperClass没有更具体的method()声明,因此在调用c3.method()时仍然使用Protocol.method().
如果你定义类似的东西:
let c4 = SubClass()
… c4是SubClass类型.由于SubClass确实有一个更具体的method()声明,因此在调用c4.method()时会使用SubClass.method().
您也可以通过将它转发到SubClass来获取c2来调用SubClass.method():
(c2 as! SubClass).method() // returns "From Class2"
这是SwiftStub的演示.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。