Created
January 13, 2020 21:00
-
-
Save wildthink/c28317b1d0e50d3e5701f18a596a2f14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
struct Maker { | |
var code: () -> Any | |
func make<A: Any>() -> A? { | |
return code() as? A | |
} | |
} | |
extension Maker { | |
static var table: [String: Maker] = [:] | |
static func register<A: Any>(code: @escaping () -> A) { | |
Maker.table[String(describing: A.self)] = Maker(code: code) | |
} | |
} | |
Maker.register { | |
"<random_string>" | |
} | |
// Mocking | |
@dynamicMemberLookup | |
public struct Mock<T> { | |
var value: T | |
subscript<V>(dynamicMember keyPath: KeyPath<T, V>) -> V { | |
if let maker = Maker.table[String(describing: V.self)], | |
let value: V = maker.make() { | |
return value | |
} | |
return value[keyPath: keyPath] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment