在Swift中,为什么子类方法不能覆盖超类的协议扩展所提供的方法 [英] In Swift, why subclass method cannot override the one, provided by protocol extension in superclass

查看:172
本文介绍了在Swift中,为什么子类方法不能覆盖超类的协议扩展所提供的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题的标题令人困惑,但以下示例说明了奇怪的行为:

I know the title of this question is confusing but the weird behaviour is explained in the example below:

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()为何返回相同的值?子类中的method()为什么不起作用?

How come c1.method() and c2.method() return the same? How come the method() in SubClass doesn't work?

有趣的是,在没有声明c2类型的情况下,这将起作用:

Interestingly, without declaring the type of c2, this is going to work:

let c2  = SubClass()
c2.method() // "From Class2"

推荐答案

问题是c1c2的类型为Protocol,因为您已经以这种方式明确定义了它们的类型(请记住:协议是完全成熟的类型).这意味着,在调用method()时,Swift会调用Protocol.method.

The problem is that c1 and c2 are of type Protocol, as you've defined their type explicitly this way (remember: protocols are fully fledged types). This means, when calling method(), Swift calls Protocol.method.

如果您定义如下内容:

let c3 = SuperClass()

... c3的类型为SuperClass.由于SuperClass没有更具体的method()声明,因此在调用c3.method()时仍使用Protocol.method().

...c3 is of type SuperClass. As SuperClass has no more specific method() declaration, Protocol.method() is still used, when calling c3.method().

如果您定义如下内容:

let c4 = SubClass()

... c4的类型为SubClass.由于SubClass确实具有更具体的method()声明,因此在调用c4.method()时将使用SubClass.method().

...c4 is of type SubClass. As SubClass does have a more specific method() declaration, SubClass.method() is used, when calling c4.method().

您还可以通过将SubClass.method()向下广播到`SubClass:

You could also get c2 to call SubClass.method(), by down-casting it to `SubClass:

(c2 as! SubClass).method() // returns "From Class2"


这是 SwiftStub 上的演示.


Here's a demonstration on SwiftStub.

这篇关于在Swift中,为什么子类方法不能覆盖超类的协议扩展所提供的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆