-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
Typecasting is a way to check the type of the instance and/or to treat the instance as a specific type. In Swift, we would use the is keyword to check whether an instance is a specific type and the as keyword to treat an instance that conforms to a protocol as a concrete type.
Let’s see how we would check the instance type using the is keyword. The following example shows how this is done:
for person in people {
if person is SwiftProgrammer {
print("\(person.firstName) is a Swift Programmer")
}
}
In this example, we use the if conditional statement to check whether each element within the people array is an instance of the SwiftProgrammer type and, if so, we print that the person is a Swift programmer.
As previously mentioned, the as keyword is used to treat the instance as a specific type. In the next example, we use the if-let conditional statement to check the instance type:
for person in people {...