How to get parent / superclass reference in Swift?

In Swift, you can create inheritance:

class A { } class B:A { } 

In this example, B inherits from A If I create a function inside B, is there a way to get a super class A reference to it? I thought it would be something like:

 self.super 

Or

 self.super() 

or

 self.parent 

I tried all this and no one worked for me. Does anyone know how to get a link to a superclass?

+5
source share
4 answers

You need to import the Objective-C runtime, and then you can use class_getSuperclass() .

 import ObjectiveC class A {} class B:A { func mySuper() -> AnyClass { return class_getSuperclass(self.dynamicType) } } B().mySuper() // A.Type 

It is very unlikely that this is a good idea for anything other than debugging and logging. Even then, it is very non-Swiftlike, and you must deeply rethink your problem before pursuing it. Even subclasses like this are pretty different from Swift. Protocols and extensions are almost always a better solution than inheriting pure Swift (and without inheritance there is no need to worry about superclasses).

+1
source
 class A { func f() { print("A") } } class B : A { override func f() { print("B") super.f() } } let b = B() bf() 
0
source
 class A { var type: AnyClass { return A.self } } class B : A { override var type: AnyClass { return B.self } var superType: AnyClass { return super.type} } let type = B().type let superType = B().superType 
0
source

Given the class A : B , I was able to just call self.superclass inside B after importing ObjectiveC .

0
source

Source: https://habr.com/ru/post/1234755/


All Articles