DShah
DShah

Reputation: 9876

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

Upvotes: 6

Views: 7125

Answers (3)

Hieu Nguyen
Hieu Nguyen

Reputation: 1

let childObj = baseObj
switch childObj {
    case let _child as Child: 
        _child.someFunc()
    default: break
}

Upvotes: -1

Owais Munawar
Owais Munawar

Reputation: 66

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

Upvotes: 1

Abhinav
Abhinav

Reputation: 38162

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

Upvotes: 5

Related Questions