通过镜像在Swift中进行反射

  • Mirror

    • value: 访问原始反射值,但类型为 Any。
    • valueType: 原始反射值的类型,相当于 value.dynamicType。
  • 我没有发现任何方法可以用纯 Swift 对象给$0.value赋值,所以Class继承NSObjectKVC

  • 我忽略了简化的可选情况。

  • 递归生成字典或对象

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
import Foundation

typealias DynamicKVType = [String: Any]
protocol DynamicKV {
func dict() -> DynamicKVType
func assignment(_ with: DynamicKVType)
}
extension DynamicKV {
func dict() -> DynamicKVType {
var dict = DynamicKVType()

Mirror(reflecting: self).children.forEach {
guard let k = $0.label else { return }
if let v = $0.value as? DynamicKV {
dict[k] = v.dict()
} else {
dict[k] = $0.value
}
}
return dict
}

func assignment(_ with: DynamicKVType) {
Mirror(reflecting: self).children.forEach {
guard let obj = self as? NSObject, let dictV = with[$0.label!], let k = $0.label else { fatalError("child leak") }

if let dkvt = dictV as? DynamicKVType, let v = $0.value as? DynamicKV {
v.assignment(dkvt)
} else {
obj.setValue(dictV, forKey: k)
}
}
}

}

class A: NSObject, DynamicKV {
var s: String = "a"
var i: Int = -1
}

class B: NSObject, DynamicKV {
var s = "b"
var a = A()
var array = [0, 1, 2, 3]
}

let b = B()
print("b.dict\t", b.dict())

b.assignment(["s": "bbbbbbb", "a": ["s": "aaaaaaa", "i": 233], "array": [-3, -2, -1]])
print("b.assignment\t", b.s, b.a.s, b.a.i, b.array)