Skip to content

Instantly share code, notes, and snippets.

@wildthink
Created January 13, 2020 21:00
Show Gist options
  • Save wildthink/c28317b1d0e50d3e5701f18a596a2f14 to your computer and use it in GitHub Desktop.
Save wildthink/c28317b1d0e50d3e5701f18a596a2f14 to your computer and use it in GitHub Desktop.
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