Polymorphism in Swift

What is it and how can we implement it in Swift?

Image for post
Image for post

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.

Protocols

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]

Works fine.

Downcasting

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:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store