假设这三个类具有这种简单的层次结构: 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中
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中实现呢?
super.foo()应该足够了,因为B打印“B”并调用super来打印“A”.class C: B { override func foo() { super.foo() print("C") } }
let c = C() c.foo()
输出:
A B C
如果你想故意从B公开A的foo(),你需要创建一个新的访问者:
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 } }