Downcasting fails

1.1k views Asked by At

I encountered little unusual down casting failure.

I have a class Vehicle in FrameworkA

FrameworkA

open class Vehicle {
    open var name: String = ""
}

And I subclassed this Vehicle class in other project.

Project

import FrameworkA

class Car: Vehicle {
    var maker: String = ""
}

And I tried downcast like this

let vehicle = Vehicle()
let car = vehicle as! Car

If they are in same framework(or same project namespace), there is no problem, but in this case down casting from Vehicle to Car fails.

The error message was just like below.

Could not cast value of type 'FrameworkA.Vehicle' (0x1070e4238) to 'Project.Car' (0x10161c120).

So I had to use extension of Vehicle class and used associatedObject. Is there any way to subclass and downcast?

2

There are 2 answers

0
rmaddy On BEST ANSWER

Of course your code fails. It has nothing to do with using a framework or not.

Car is a special kind of Vehicle. You are creating a Vehicle object. You then try to cast it to a Car. But it's not a Car. It's a Vehicle.

The following works:

let car = Car()
let vehicle: Vehicle = car

That's fine because you create a Car which is also a Vehicle.

You can also do this:

let vehicle: Vehicle = Car()
let car = vehicle as! Car

That works because even though vehicle is declared as a Vehicle, the object it is actually pointing to is a Car.

1
Daniel Hall On

This isn't a downcast... Car is a Vehicle, but Vehicle isn't a Car.