Polymorphism with protocols
What we saw 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 the previous example where we created an array of the PersonProtocol
types and looped through the array. We can then access each item in the array using the properties and methods defined 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)")
}
When we define the type of a variable, constant...