Swift Type Erasure: Flexible and Modular Code Creation

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
March 30, 2024
Advanced Swift Patterns: Type Erasure

Advanced Swift Patterns: Type Erasure

Type erasure is a powerful technique in Swift that allows you to abstract away concrete types and work with protocols instead. This can be particularly useful when you need to store objects of different types that conform to a common protocol in a collection, or when you want to hide implementation details from the user of your API.

Let's look at an example of how type erasure can be implemented using a protocol with associated type:

protocol AnyPrinter {
    func print(_ value: Any)
}

struct ConsolePrinter: AnyPrinter {
    func print(_ value: Any) {
        Swift.print("Printing value: \(value)")
    }
}

struct FilePrinter: AnyPrinter {
    func print(_ value: Any) {
        // Implement file printing logic here
    }
}

struct PrinterContainer {
    private var printer: AnyPrinter

    init(printer: AnyPrinter) {
        self.printer = printer
    }

    func printValue(_ value: Any) {
        printer.print(value)
    }
}

let consolePrinter = ConsolePrinter()
let printerContainer = PrinterContainer(printer: consolePrinter)
printerContainer.printValue("Hello, World!")}

In the example above, we define a protocol `AnyPrinter` with a single method `print(_ value: Any)`. We then create two concrete implementations of this protocol - `ConsolePrinter` and `FilePrinter`. We use a struct `PrinterContainer` to store an instance of `AnyPrinter` and provide a method to print values using the stored printer.

By using type erasure, we can store instances of different types that conform to the `AnyPrinter` protocol in `PrinterContainer`, without exposing the concrete types to the user of the `PrinterContainer` API.

Type erasure is a powerful technique that can help you write more flexible and modular code in Swift. It allows you to work with protocols and hide implementation details, leading to more reusable and maintainable code.