What we were seeing in the previous examples is a form of polymorphism. The word polymorphism comes from the Greek roots Poly, meaning many, and morphe, meaning form. In programming languages, polymorphism is a single interface to multiple types (many forms). In the previous example, the single interface was the PersonProtocol
protocol and the multiple types were any type that conforms to that protocol.
Polymorphism gives us the ability to interact with multiple types in a uniform manner. To illustrate this, we can extend our previous example where we created an array of the PersonProtocol
types and loop through the array. We can then access each item in the array using the properties and methods define in the PersonProtocol
protocol, regardless of the actual type. Let's see an example of this:
for person in people { print("\(person.firstName) \(person.lastName): \(person.profession)") }
If we ran this example, the output would look similar to this...