迅捷继承:超级的超级 [英] Swift Inheritance: Super's Super

查看:65
本文介绍了迅捷继承:超级的超级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这三个类具有简单的层次结构:

Supposing to have this three classes with this simply hierarchy:

class A {
    func foo() {
       print("A")
    }
}

class B: A {
    override func foo() {
       super.foo()
       print("B")
    }
}

class C: B {
    override func foo() {
       // *******
       print("C")
    }
}

在C类中,在覆盖的方法 foo 中,我想调用方法foo:,这可能吗?

In class C, in overrided method foo I want to call a method foo: is it possible?

在C ++中,这可以通过C->A::foo()实现,但是我该如何在Swift中做到这一点?

In C++ this can be achieved with C->A::foo(), but how do I do this in Swift?

推荐答案

super.foo()应该足够了,因为B打印"B"并调用super打印"A".

super.foo() should be sufficient, since B prints "B" and calls super to print "A".

class C: B {
    override func foo() {
        super.foo()
        print("C")
    }
}

let c = C()
c.foo()

输出:

A
B
C

如果要有意从B公开Afoo(),则需要创建一个新的访问器:

If you want to intentionally expose A's foo() from B, you need to create a new accessor:

class B: A {
    override func foo() {
        super.foo()
        print("B")
    }

    func exposeFoo() {
        super.foo()
    }
}

class C: B {
    override func foo() {
        super.exposeFoo()
        print("C")
    }
}

或者,使用NSObject和Objective-C运行时的功能:

Or, use NSObject and the power of the Objective-C runtime:

class A: NSObject { // make sure your base class inherits from NSObject
    func foo() {
        print("A")
    }
}

// ...

class C: B {
    override func foo() {

        guard let superSuper = self.superclass?.superclass() else {
            return; // no super super
        }

        let fooImp = class_getMethodImplementation(superSuper, "foo")

        typealias MyCFunction = @convention(c) (AnyObject, Selector) -> Void
        let curriedImplementation = unsafeBitCast(fooImp, MyCFunction.self)
        curriedImplementation(self, selector) // prints A
    }
}

这篇关于迅捷继承:超级的超级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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