Skip to content

Instantly share code, notes, and snippets.

@sundeepgupta
Created February 6, 2017 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sundeepgupta/f90ba84c3eb9734271e18369c4885edb to your computer and use it in GitHub Desktop.
Save sundeepgupta/f90ba84c3eb9734271e18369c4885edb to your computer and use it in GitHub Desktop.
Swift Type Erasure Example
import UIKit
protocol Decodable {
func decode() -> Void
}
struct Action {
let decodable: AnyDecodable
}
protocol Requestable {
func perform(action: Action)
}
struct AnyDecodable: Decodable {
let _decode: () -> Void
init<D: Decodable>(_ decodable: D) {
_decode = decodable.decode
}
func decode() {
_decode()
}
}
extension String: Decodable {
func decode() { print(self) }
}
let s = "hello"
let erased = AnyDecodable(s)
erased.decode()
class MockRequestable: Requestable {
var action: Action!
init() {}
func perform(action: Action) {
self.action = action
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment