Polymorphism

Swift is a young language, but incorporates many old ideas and contains all features that have become standard in object-oriented programming languages.

Polymorphism is one of these standards - it describes the concept that objects of different types can be accessed through the same interface. Since all objects have the same interface, Swift needs to somehow determine which interface belongs to which object - this is done by Method Dispatch.

This is a very basic example of Polymorphism with Swift classes:

class Animal {
    func makeNoise() {
        print("Animal is making a sound")
    }
}

class Dog: Animal {
    override func makeNoise() {
        print("Wuff")
    }
}

class Cat: Animal {
    override func makeNoise() {
        print("Meow")
    }
}

let dog = Dog()
let cat = Cat()

[dog, cat].forEach { $0.makeNoise() }
// Wuff Meow

Since we declared the method makeNoise() inside the initial declaration of a class, Swift will automatically dynamically dispatch these methods.

One very important feature in Swift is that Polymorphism can also be achieved with structs conforming to the same protocol - in this case, the compiler will create witness tables for each struct.

protocol Noisy {
    func makeNoise()
}

struct Dog: Noisy {
     func makeNoise() {
        print("Wuff")
    }
}

struct Cat: Noisy {
     func makeNoise() {
        print("Meow")
    }
}

let dog = Dog()
let cat = Cat()
let animals: [Noisy] = [dog, cat]

animals.forEach { $0.makeNoise() }
// Wuff Meow
Written on May 11, 2019