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?
Of course your code fails. It has nothing to do with using a framework or not.
Car
is a special kind ofVehicle
. You are creating aVehicle
object. You then try to cast it to aCar
. But it's not aCar
. It's aVehicle
.The following works:
That's fine because you create a
Car
which is also aVehicle
.You can also do this:
That works because even though
vehicle
is declared as aVehicle
, the object it is actually pointing to is aCar
.