In Swift you can create inheritance:
class A {
}
class B:A {
}
In this example B
inherits from A
. If I create a function within B is there a way I can get a reference to it's super class A
? I was thinking it would be something like:
self.super
Or
self.super()
Or
self.parent
I tried all of these and none worked for me. Does anyone know how to get a reference to the super class?
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.
Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
The init() initializer for Bicycle starts by calling super. init(), which calls the default initializer for the Bicycle class's superclass, Vehicle. This ensures that the numberOfWheels inherited property is initialized by Vehicle before Bicycle has the opportunity to modify the property.
Inheritance allows us to create a new class from an existing class. The new class that is created is known as subclass (child or derived class) and the existing class from which the child class is derived is known as superclass (parent or base class). Here, we are inheriting the Dog subclass from the Animal superclass.
A pure Swift version of this, that works on Linux, but relies on a not-quite-official API is:
class A {}
class B: A {}
let superclass = Swift._getSuperclass (B.self)
print ("\(superclass)")
Thanks to gwynne-raskind for the help!
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 extremely unlikely that this is a good idea for anything other than debugging and logging. Even then, it is very un-Swiftlike, and you should deeply rethink your problem before pursuing it. Even subclassing like this is pretty un-Swiftlike. Protocols and extensions are almost always a better solution than inheritance in pure Swift (and without inheritance, there is no need to worry about superclasses).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With