Type Casting in Swift: Using as? and as!

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

by The Captain

on
March 28, 2024

Working with Type Casting in Swift

Type casting allows you to check the type of an instance and treat it as a different super or subclass type. This is useful when working with class hierarchies or protocols in Swift.

There are two types of type casting in Swift: as? which performs a conditional cast and returns an optional value if the cast is successful, and as! which performs a forced cast and can cause a runtime error if the cast fails.

Here's an example of how to use type casting in Swift:

class Animal {
    func speak() {
        print("Animal makes a sound")
    }
}

class Dog: Animal {
    func bark() {
        print("Dog barks")
    }
}

let myDog = Dog()
let myAnimal: Animal = myDog

if let dog = myAnimal as? Dog {
    dog.bark() // Output: Dog barks
}

if let animal = myAnimal as? Animal {
    animal.speak() // Output: Animal makes a sound
}

let anotherAnimal = Animal()
let anotherDog = anotherAnimal as? Dog

if anotherDog == nil {
    print("Not a Dog")
}

In the code snippet above, we have a class hierarchy where Dog is a subclass of Animal. We create an instance of Dog and assign it to an Animal type variable. We then use as? to conditionally cast it back to a Dog instance and call the bark method. We also demonstrate checking for unsuccessful casting using optional binding and the as? operator.

Remember to use type casting carefully, as forced casting using as! can lead to runtime errors if the types are not compatible. Always prefer conditional casting using as? and handle the optional values appropriately.