Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Type Cast from Parent/Base to Child class

I have parent/base class as below:

class Base {
    ...
}

Also, having the child class as below:

class Child: Base {
    ...
    func someFunc() {

    }
}

I have created the instances of Parent class as below:

let baseObj = Base()

Now, I want to call the method of Child class from the parent object. So I have code like below:

let childObj = baseObj as! Child
childObj.someFunc()

But this is giving me runtime crash like below:

Could not cast value of type 'PCTests.Base' (0x11c6ad150) to 'PCTests.Child' (0x11c6ab530).
like image 339
DShah Avatar asked Oct 06 '15 04:10

DShah


People also ask

Can you cast from parent to child?

However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it's not possible, the compiler throws a ClassCastException.

What is Upcasting and Downcasting in Swift?

Downcasting is the opposite of upcasting, and it refers to casting an object of a parent class type to an object of its children class. Downcasting is used to reconvert objects of a children class that were upcasted earlier to generalize. Let's say you own two cars and three trucks.

Can you typecast a parent to child in Java?

In Java, we cannot assign a parent class reference object to the child class, but if we perform downcasting, we will not get any compile-time error.

Can parent class instantiate child class?

Following the object oriented methodology, a child class can be instantiated as an object that can inherit the attributes of the parent class. This is the process of inheritance, much like how a benefactor can pass on their wealth or assets to a beneficiary.


2 Answers

Error says it all.... You cannot typecast parent into child object. Thats not how inheritance works.

like image 57
Abhinav Avatar answered Sep 28 '22 11:09

Abhinav


You can achieve that by making object of child class actually, and you should keep structure in that way as this is core concept of Base and child class, if you do following it should work:

let baseObj = Child()

Now in base class you can do following

let childObj = self as! Child
childObj.someFunc()

Whereas someFunc is defined in child class.

P.S. Would be my pleasure to clarify if it doesn't make sense for you, thanks

like image 24
Owais Munawar Avatar answered Sep 28 '22 10:09

Owais Munawar