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 is2 associatedtype Output3 func produce() -> Output4}5 // The type-erased wrapper: only the Output type T remains visible6struct AnyPrintable<T>: Printable { // Stores the behavior as a closure instead of the concrete value's type7 private let _produce: () -> T8 // Accepts any Printable P whose Output is T9 init<P: Printable>(_ printable: P) where P.Output == T { // Keeps a reference to the wrapped value's method; P's type is forgotten10 _produce = printable.produce11 }12 // Forwards the call to the stored closure13 func produce() -> T {14 return _produce()15 }16}17 // Output is inferred as String18struct StringProducer: Printable {19 func produce() -> String { return "Hello" }20}21 // Output is Int; it would need an AnyPrintable<Int> array, so it is not used22struct IntProducer: Printable {23 func produce() -> Int { return 42 }24}25 // An array of the erased type, holding a wrapped StringProducer26let producers: [AnyPrintable<String>] = [27 AnyPrintable(StringProducer())28]29for p in producers { // Calls through the wrapper: prints Hello30 print(p.produce())31}Output
Hello
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