Type Erasure in Swift

Level 5541 keystrokes

Before Swift 5.7, a protocol with an associated type could not be used directly as an array element type. The wrapper AnyPrintable<T> stores the wrapped value's produce method as a closure and hides its concrete type, so values of different types with the same Output can share an array. It prints Hello.

Swift code

1protocol Printable {
// Each conforming type decides what Output is
2 associatedtype Output
3 func produce() -> Output
4}
5
// The type-erased wrapper: only the Output type T remains visible
6struct AnyPrintable<T>: Printable {
// Stores the behavior as a closure instead of the concrete value's type
7 private let _produce: () -> T
8
// Accepts any Printable P whose Output is T
9 init<P: Printable>(_ printable: P) where P.Output == T {
// Keeps a reference to the wrapped value's method; P's type is forgotten
10 _produce = printable.produce
11 }
12
// Forwards the call to the stored closure
13 func produce() -> T {
14 return _produce()
15 }
16}
17
// Output is inferred as String
18struct StringProducer: Printable {
19 func produce() -> String { return "Hello" }
20}
21
// Output is Int; it would need an AnyPrintable<Int> array, so it is not used
22struct IntProducer: Printable {
23 func produce() -> Int { return 42 }
24}
25
// An array of the erased type, holding a wrapped StringProducer
26let producers: [AnyPrintable<String>] = [
27 AnyPrintable(StringProducer())
28]
29for p in producers {
// Calls through the wrapper: prints Hello
30 print(p.produce())
31}

Output

Hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 11
  • )× 11
  • {× 9
  • }× 9
  • >× 8
  • :× 7
  • -× 5
  • _× 4
  • =× 4
  • .× 3

More Swift examples at level 5

← Swift typing practice