NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

When is type casting useful in Swift?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Type casting lets us tell Swift that an object it thinks is type A is actually type B, which is helpful when working with protocols and class inheritance.

As you’ve seen, protocols let us group together common functionality so we can share code. However, some times we need to go in the opposite direction – we need to be able to see “you have an object that conforms to a protocol, but I’d like you to let me use it as a specific type.”

To demonstrate this, here’s a simple class hierarchy:

class Person {
    var name = "Anonymous"
}

class Customer: Person {
    var id = 12345
}

class Employee: Person {
    var salary = 50_000
}

I’ve used default values for each property so we don’t need to write an initializer.

We can create an instance of each of those, and add them to the same array:

let customer = Customer()
let employee = Employee()
let people = [customer, employee]

Because both Customer and Employee inherit from Person, Swift will consider that people constant to be a Person array. So, if we loop over people we’ll only be able to access the name of each item in the array – or at least we would only be able to do that, if it weren’t for type casting:

for person in people {
    if let customer = person as? Customer {
        print("I'm a customer, with id \(customer.id)")
    } else if let employee = person as? Employee {
        print("I'm an employee, earning $\(employee.salary)")
    }
}

As you can see, that attempts to convert person first to Customer and then to Employee. If either test passes, we can then use the extra properties that belong to that class, as well as the name property from the parent class.

Type casting isn’t specifically frowned upon in Swift, but I would say that repeated type casting might mean you’ve got an underlying problem in your code. More specifically, Swift works best when it understands what data you’re working with, and a type cast effectively says to Swift, “I know more information than you do.” If you can find ways to convey that information to Swift so it understand it as well, that usually works better.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.