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?
- Classes, structs and some idea of inheritence
- The idea that abstract classes fulfil contracts
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.
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.
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.
Is it possible to do the same with Protocols in Swift?
Well. Yes. Yes, it is. Note that polymorphism as applied to protocols can also be applied to structs, making this a very flexible way to apply polymorphism when coding in Swift.
Incidentally this also works implicitly, that is for an array we do not need to declare the type for our array.
So in the above example:
var arr = [a,b]
In either case (inheritance polymorphism or protocol polymorphism) we can use downcasting from the array.
The following is not a great example, but hey it works.
Want to get in contact? Try the link here: