Type casting with protocols

Type casting is a way to check the type of the instance and/or to treat the instance as a specified type. In Swift, we use the is keyword to check if an instance is a specific type and the as keyword to treat the instance as a specific type.

To start with, let's see how we would check the instance type using the is keyword. The following example shows how would we do this:

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 in the people array is an instance of the SwiftProgrammer type and if so, we print that the person is a Swift programmer to the console. While this is a good method ...

Get Mastering Swift 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.