Member-only story
How to use type erasure in Swift with a real example
Unlocking flexibility and reusability by mastering type erasure in Swift
One of the remarkable attributes of Swift is its strong focus on type safety, which ensures a robust and reliable codebase.
However, we might find ourselves in situations where we need a little more flexibility. We might want to hide or abstract a specific value type to make our code more generic and reusable. We want to type erasure.
This is a powerful technique that, as an iOS developer, you should master. Because, sooner or later, you will need to use it.
Let’s jump into a practical example to see how it works.
Our coffee shop app allows our customers to add coffee drinks and food to their orders. As we have different sizes for the coffees than for the food, we could model our entities as follow:
struct Coffee {
enum CoffeeType {
case latte
case cappuccino
case mocha
}
enum CoffeeSize {
case small
case medium
case large
}
let type: CoffeeType
let size: CoffeeSize
private let prices: [CoffeeType: [CoffeeSize: Float]] = [
.latte: [
.small: 4.5,
.medium: 5.5,
.large: 6.0…