Skip to content

Instantly share code, notes, and snippets.

@tarunon
Last active March 15, 2018 04:51
Show Gist options
  • Save tarunon/6da5e305f49e67757dfd353603baa8c9 to your computer and use it in GitHub Desktop.
Save tarunon/6da5e305f49e67757dfd353603baa8c9 to your computer and use it in GitHub Desktop.
Protocol+Class+Erasure.swift
class Animal: AnimalConvertible {
func bark() -> String { fatalError() }
func asAnimal() -> Animal {
return self
}
}
protocol AnimalConvertible {
func bark() -> String
func asAnimal() -> Animal
}
protocol AnimalProxy: AnimalConvertible {
associatedtype Animal: AnimalConvertible
var animal: Animal { get }
}
extension AnimalProxy {
@inline(__always)
func bark() -> String {
return animal.bark()
}
}
private class Box<A: AnimalConvertible>: Animal {
let a: A
init(a: A) {
self.a = a
}
override func bark() -> String {
return a.bark()
}
}
extension AnimalConvertible {
func asAnimal() -> Animal {
return Box(a: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment