Last active
October 22, 2016 04:48
-
-
Save rudyjahchan/4cd889a9d4c1a8776aa987e5e557c897 to your computer and use it in GitHub Desktop.
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
//: 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