Type Casting in Swift: Implementation and Examples

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 24, 2024
Implementing Type Casting in Swift

Implementing Type Casting in Swift

Type casting in Swift allows you to check and interpret the type of an instance at runtime. This feature is particularly useful when working with hierarchies of classes or protocols. In Swift, you can use two operators for type casting: as? and as!.

The as? operator performs a conditional cast, which will return an optional value of the desired type if the instance can be cast to that type. If the cast fails, the result will be nil.

The as! operator, on the other hand, performs a forced cast. If the instance cannot be cast to the desired type, a runtime error will occur.

Here is a simple example demonstrating how to use type casting in Swift:

class Vehicle {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Car: Vehicle {
    var color: String
    init(name: String, color: String) {
        self.color = color
        super.init(name: name)
    }
}

class Boat: Vehicle {
    var length: Int
    init(name: String, length: Int) {
        self.length = length
        super.init(name: name)
    }
}

let vehicles: [Vehicle] = [Car(name: "BMW", color: "Red"), Boat(name: "Yacht", length: 50)]

for vehicle in vehicles {
    if let car = vehicle as? Car {
        print("Car: \(car.name), Color: \(car.color)")
    } else if let boat = vehicle as? Boat {
        print("Boat: \(boat.name), Length: \(boat.length) meters")
    }
}

In this code snippet, we have a base class Vehicle and two subclasses Car and Boat. By using the as? operator, we check if each element in the vehicles array can be cast to either a Car or a Boat, and then print out the specific details accordingly.

By leveraging type casting in Swift, you can handle instances of different types in a hierarchy more efficiently and safely.