Swift Type Casting: Real-World Examples and Best Practices

Ferdous Mahmud Akash

Ferdous Mahmud Akash

· 3 min read
Swift type Casting

Type Casting

Type casting is the process of checking the type of an instance at runtime and converting it to another type if possible. For example,

class Vehicle {
    var numberOfWheels: Int
    var isEV: Bool
    var color: String
    
    init(numberOfWheels: Int, isEV: Bool, color: String) {
        self.numberOfWheels = numberOfWheels
        self.isEV = isEV
        self.color = color
    }
}

In this example, we define a Vehicle class. Let's define a Car and Bus subclass that inherits from the Vehicle superclass.

class Car: Vehicle {
    var model: String
    var brand: String
    
    init(numberOfWheels: Int, isEV: Bool, color: String, model: String, brand: String) {
        self.model = model
        self.brand = brand
        super.init(numberOfWheels: numberOfWheels, isEV: isEV, color: color)
    }
    
    func drive() {
        print("Vroom vroom!")
    }
}

class Bus: Vehicle {
    var numberOfSeats: Int
    
    init(numberOfWheels: Int, isEV: Bool, color: String, numberOfSeats: Int) {
        self.numberOfSeats = numberOfSeats
        super.init(numberOfWheels: numberOfWheels, isEV: isEV, color: color)
    }
    
    override func honk() {
        print("Beep beep!")
    }
}

Now creating a vehicleArray that has a common Vehicle type of elements.

let vehicle1 = Vehicle(numberOfWheels: 4, isEV: false, color: "red")
let vehicle2 = Car(numberOfWheels: 4, isEV: true, color: "blue", model: "Model 3", brand: "Tesla")
let vehicle3 = Bus(numberOfWheels: 6, isEV: false, color: "yellow", numberOfSeats: 30)

let vehicleArray: [Vehicle] = [vehicle1, vehicle2, vehicle3]

In order to work with them as their native type, you need to check their type or downcast them to a different type, as described below.

Upcasting

Upcasting is the process of converting an instance of a subclass to an instance of its superclass. This is always safe because the subclass instance is guaranteed to have all the properties and methods of its superclass. You can upcast a value to a superclass type by using the `as` keyword, like this:

let myCar: Car = Car(numberOfWheels: 4, isEV: true, color: "blue", model: "Model 3", brand: "Tesla")
let myVehicle: Vehicle = myCar as Vehicle

Downcasting

Downcasting is the process of converting an instance of a superclass to an instance of its subclass. This is potentially unsafe because the superclass instance may not have all the properties and methods of its subclass. You can downcast a value to a subclass type by using the optional downcast operator (as?) or the forced downcast operator (as!), like this:

let myVehicle: Vehicle = Vehicle(numberOfWheels: 2, isEV: false, color: "red")

// Optional downcast
if let myCar = myVehicle as? Car {
    print("This is a car with model \(myCar.model) and brand \(myCar.brand)")
} else {
    print("This is not a car")
}

// Forced downcast
let myOtherVehicle: Vehicle = Car(numberOfWheels: 4, isEV: true, color: "black", model: "Model X", brand: "Tesla")
let myOtherCar = myOtherVehicle as! Car
print("This is a car with model \(myOtherCar.model) and brand \(myOtherCar.brand)")

Swift also provides a type check operator (is) to check whether an instance is of a certain type. This is useful for conditional type casting or for checking the type of an instance before using it in a particular way. For example,

let myVehicle: Vehicle = Car(numberOfWheels: 4, isEV: true, color: "white", model: "i3", brand: "BMW")

if myVehicle is Car {
    print("This is a car")
} else {
    print("This is not a car")
}

In conclusion, type casting is an important concept in Swift that allows us to work with different types of objects in a flexible and dynamic way. We can use type casting to check the type of an object at runtime, to convert an object from one type to another, and to upcast or downcast objects to work with them as instances of their superclass or subclass.

Swift provides several ways to perform type casting, including the is and as operators, as well as the as? and as! keywords. By using these tools, we can write code that is more modular, reusable, and extensible, since we can work with objects of different types without having to know their specific type at compile time.

Whether you are working with a large codebase or a small project, type casting is an essential skill to have in your toolkit as a Swift developer. By mastering the art of type casting, you can take your coding skills to the next level and build more sophisticated and robust applications. Happy Coding 🚀

Ferdous Mahmud Akash

About Ferdous Mahmud Akash

Hey there! I'm a self-taught iOS developer from Bangladesh.

I'm also passionate about sharing my knowledge and experience with other aspiring developers through my blog at ferdousmahmud.co

Thank you for visiting my website, and feel free to reach out if you have any questions or just want to say hello!

Copyright © 2021-2024 Ferdous Mahmud Akash. All rights reserved.
Made by Ferdous· Github
LinkTree