Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
When is type casting useful in Swift? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

When is type casting useful in Swift?

Paul Hudson    @twostraws   

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 NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.