Defining Polymorphism in Swift

Polymorphism is the ability for different types to be treated as a common type. In the context of Swift, this means that you can write functions and methods that operate on values of a protocol type, and they will work with any type that conforms to the protocol.

For example, you could define a protocol called Shape that defines a method for calculating the area of a shape, and then have different types of shapes (such as a circle, square, and triangle) adopt that protocol and implement the calculateArea method in their own way. You could then write a function that takes a Shape as its parameter, and this function would be able to operate on any type of shape (such as a circle, square, or triangle) that conforms to the Shape protocol.

Polymorphism allows for more generic, reusable code, as it allows you to write code that operates on a protocol type and can be used with any type that conforms to that protocol. This can help you avoid repeating code and make your code more flexible and maintainable.

Here is an example of polymorphism in Swift:

protocol Shape {
    func calculateArea() -> Double
}

struct Circle: Shape {
    var radius: Double

    func calculateArea() -> Double {
        return Double.pi * radius * radius
    }
}

struct Square: Shape {
    var sideLength: Double

    func calculateArea() -> Double {
        return sideLength * sideLength
    }
}

struct Triangle: Shape {
    var base: Double
    var height: Double

    func calculateArea() -> Double {
        return 0.5 * base * height
    }
}

let circle = Circle(radius: 5)
let square = Square(sideLength: 10)
let triangle = Triangle(base: 5, height: 10)

let shapes: [Shape] = [circle, square, triangle]

for shape in shapes {
    print(shape.calculateArea())
}

In this example, the Shape protocol defines a method for calculating the area of a shape, and the Circle, Square, and Triangle structs adopt this protocol and implement the calculateArea method in their own way. The shapes array is defined as an array of Shape values, and it contains instances of each of the three shapes.

When the for loop iterates over the shapes array, it calls the calculateArea method on each shape in the array, and the correct implementation of the calculateArea method is called for each shape, based on its type. This demonstrates how polymorphism allows for different types to be treated as a common type, and how a single function can operate on a variety of types that conform to a common protocol.

Previous
Previous

CRUD app

Next
Next

What does having “Scalable Code“ mean?