O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 whether 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 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 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required