Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Polymorphism in Swift
Written by Team Kodeco

Polymorphism in Swift allows objects of different classes to be treated as objects of a common superclass or protocol. It enables objects of different types to be used interchangeably, as long as they conform to a common interface or protocol.

Here’s an example of how to use polymorphism with a superclass and its subclasses:

class Shape {
  func draw() {
    print("Drawing a shape")
  }
}

class Circle: Shape {
  override func draw() {
    print("Drawing a circle")
  }
}

class Square: Shape {
  override func draw() {
    print("Drawing a square")
  }
}

This creates a new superclass called Shape with a method called draw that prints “Drawing a shape”.

Then, two new subclasses called Circle and Square are defined, which inherit from the Shape class. They override the draw method to print “Drawing a circle” and “Drawing a square” respectively.

You can create an instance of the subclasses and use them interchangeably with the superclass:

func drawShape(shape: Shape) {
  shape.draw()
}
drawShape(shape: Circle()) // prints "Drawing a circle"
drawShape(shape: Square()) // prints "Drawing a square"

In this example, the function drawShape takes a Shape as an argument. It means that the function expects an object that conforms to the interface defined by the Shape class. But, you can pass in instances of a Circle or Square to the function.

As Circle and Square classes inherit from the Shape class and override the draw method, they can be used interchangeably with the Shape class.

This is the fundamental concept of polymorphism. It allows you to write more flexible and reusable code.

© 2024 Kodeco Inc.