Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to a parent/super class in Swift?

Tags:

ios

swift

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?

like image 799
Axel Foley Avatar asked Oct 29 '15 01:10

Axel Foley


People also ask

What is Subclassing in Swift?

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.

Is superclass the same as parent class?

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).

What is super init () Swift?

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.

How do you get inheritance in Swift?

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.


2 Answers

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!

like image 181
miguel.de.icaza Avatar answered Oct 02 '22 17:10

miguel.de.icaza


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).

like image 33
Rob Napier Avatar answered Oct 02 '22 16:10

Rob Napier