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.
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!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.