Polymorphism in Swift
What is it and how can we implement it in Swift?
Polymorphism is an important tool for use in OO programs. But what is it, and how can we use this language feature of Swift?
Prerequisites:
- Classes, structs and some idea of inheritence
- The idea that abstract classes fulfil contracts
Terminology
Polymorphism: This is the ability of an object to take on many forms, with a common using being a parent class reference to refer to a child class object.
Inheritance: The abililty to inherit attributes and methods from another class.
Motivation
You have a superclass of an animal that can make sounds. Subclasses of animals have their own implementation of a sound (to complete the contract of being an animal). This means that a pig can be treated as a pig, or as an animal depending upon your requirements.
Example
We can do just that. We have a pig and a dog class that inherit from animal and implement animalSound respectively. We are able to upcast to a common type.