Skip to content

Instantly share code, notes, and snippets.

@siuying
Last active May 22, 2020 19:01
Show Gist options
  • Save siuying/c140778a63b92b7153ff40188f13f6d9 to your computer and use it in GitHub Desktop.
Save siuying/c140778a63b92b7153ff40188f13f6d9 to your computer and use it in GitHub Desktop.
Type erasure
import Foundation
// Base on
// https://github.com/bignerdranch/type-erasure-playgrounds/blob/master/playgrounds/Type_Erasure_Slides.playground/Contents.swift
protocol Buffer {
associatedtype T
func insert(_ value: T)
}
class ArrayBuffer<T>: Buffer {
var container: [T]
init() {
container = []
}
func insert(_ value: T) {
container.append(value)
}
}
class AnyBufferBase<T>: Buffer {
init() {
}
func insert(_ value: T) {
}
}
final class AnyBufferBox<Base: Buffer>: AnyBufferBase<Base.T> {
var base: Base
init(_ base: Base) {
self.base = base
}
override func insert(_ value: T) {
self.base.insert(value)
}
}
final class AnyBuffer<T>: Buffer {
let box: AnyBufferBase<T>
init<Base: Buffer>(_ base: Base) where Base.T == T {
box = AnyBufferBox(base)
}
func insert(_ value: T) {
self.box.insert(value)
}
}
let b1 = AnyBuffer(ArrayBuffer<String>())
b1.insert("!")
let b2 = AnyBuffer(ArrayBuffer<Int>())
b2.insert(2)
// Heterogenous collection could only be referred as Any :-(
let buffers: [String: Any] = ["string": b1, "int": b2]
let b1b = buffers["string"] as! AnyBuffer<String>
b1b.insert("Hello")
b1b.insert("World")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment