迅捷继承:超级超级

时间:2016-03-08 15:01:16

标签: swift inheritance

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

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:是否可能?

在C ++中,这可以通过C->A::foo()来实现,但是如何在Swift中实现呢?

1 个答案:

答案 0 :(得分:9)

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

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

let c = C()
c.foo()

输出:

A
B
C

如果您想故意从A公开foo() B,则需要创建新的访问者:

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运行时的强大功能:

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
    }
}