-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinder.swift
58 lines (46 loc) · 1.37 KB
/
Binder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// Binder.swift
//
// Created by Phuong Lam on 4/14/19.
// Copyright © 2019 . All rights reserved.
//
class Binding<T> {
private let binder: Binder
private let type: T.Type
private var named: String = ""
init(_ type: T.Type, binder: Binder) {
self.binder = binder
self.type = type
}
@discardableResult func to(_ any: Any) -> Binder {
return binder.bind(type, instance: any, name: self.named)
}
func withName(_ named: String) -> Binding {
self.named = named
return self
}
}
class Binder {
private var map: [String: Any] = [:]
@discardableResult func bind<T>(_ type: T.Type, instance any: Any, name: String = "") -> Binder {
map[KeyIdentifier(type: type, name: name).mkKey()] = any
return self
}
func bind<T>(_ type: T.Type) -> Binding<T> {
return Binding(type, binder: self)
}
func get<T>(_ type: T.Type, name: String = "") -> T? {
return map[KeyIdentifier(type: type, name: name).mkKey()] as? T
}
}
struct KeyIdentifier<T> {
private let type: T.Type
private let name: String
init(type: T.Type, name: String = "") {
self.name = name
self.type = type
}
func mkKey() -> String {
return "\(String(UInt(bitPattern: ObjectIdentifier(self.type))))-\(self.name)"
}
}