Created
February 6, 2017 01:02
-
-
Save sundeepgupta/f90ba84c3eb9734271e18369c4885edb to your computer and use it in GitHub Desktop.
Swift Type Erasure Example
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 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