Last active
May 22, 2020 19:01
-
-
Save siuying/c140778a63b92b7153ff40188f13f6d9 to your computer and use it in GitHub Desktop.
Type erasure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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