Type Casting in Swift

In object-oriented programming, type casting is used to treat an object as one of another type. In this article we will discuss how this works in Swift.

Car and Vehicle

Let’s start by defining the test classes car and vehicle:

Now we can declare some objects:

The interesting one here is  anotherVehicle: Its type is  Vehicle, but it is actually a  Car object. This is possible because every car is also a  Vehicle. This is an example of polymorphism.

Upcasting

You are always allowed to assign an object to a variable, which has a type that is higher in the class hierarchy. The upcast is done implicitly. In our example, Vehicle is the superclass of  Car, so the following assignment is perfectly fine:

But it is also possible to do an explicit cast by using the keyword  as:

You can always do an upcast, if you can build an “is-a sentence”. In our example,  car is a  Vehicle. The same holds true with protocols. If the class of an object implements a protocol, the object can always be assigned to an variable that has the protocol type.

You can also check the “is-a sentence” programmatically by using the keyword  is, which returns a boolean. Since  car is a  Car, you have the output “true”:

Furthermore, a  car is also  Vehicle:

Downcasting

If you want to cast down the class hierarchy, it is little bit more difficult. So  anotherVehicle has the type  Vehicle, but the object is a  Car. So we have:

It is perfectly fine to assign  anotherVehicle to a variable of the  Car type. But we are not allowed to do this without any additional twists:

We have to do an explicit cast. But just an  as is also not enough. We have to use  as! or  as?. The first can be used, if you are very sure that the cast is possible:

There would be an error at execution time, if the cast with  as! failed.

The operator  as? only performs the cast, if the cast is possible. Otherwise, it returns nil. So it is very suited to use it with optional binding:

References

Image: @ zmkstudio / shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon