Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//: Playground - noun: a place where people can play
import UIKit
typealias Properties = Dictionary<String,Any?>
struct TypeKey {
let type: Any.Type
}
extension TypeKey: Hashable {
var hashValue: Int {
return String(describing: type).hashValue
}
}
func == (lhs: TypeKey, rhs: TypeKey) -> Bool {
return lhs.type == rhs.type
}
typealias FunctionType = (Properties) -> Any
class TestFactory {
static let sharedInstance = TestFactory()
var registry = Dictionary<TypeKey,FunctionType>()
func register<T>(type: T.Type, factory: @escaping (Properties) -> T) {
let key = TypeKey(type: type)
registry[key] = factory
}
func create<T>(type: T.Type, properties: Properties = [:]) -> T? {
let key = TypeKey(type: type)
return registry[key]?(properties) as? T
}
}
func create<T>(type: T.Type, properties: Properties = [:]) -> T? {
return TestFactory.sharedInstance.create(type: type, properties: properties)
}
class Foo {
let x: Int
let y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
struct Bar {
let a: String
let b: Int
init(a: String, b: Int) {
self.a = a
self.b = b
}
}
TestFactory.sharedInstance.register(type: Foo.self) { _ in
return Foo(x: 1, y: 2)
}
TestFactory.sharedInstance.register(type: Bar.self) { properties in
let a = properties["a"] as? String ?? "Dude"
return Bar(a: a, b: 3)
}
let foo = create(type: Foo.self)
foo?.x
let bar = create(type: Bar.self, properties: ["a": "Michael"])
bar?.a
let bar2 = create(type: Bar.self)
bar2?.a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment