Reflection in Swift using Mirror

  • Mirror

    • value: Access the raw reflection value, but its type is Any.
    • valueType: The type of the raw reflection value, equivalent to value.dynamicType.
  • I didn’t find any way to assign $0.value with a pure Swift object, so Class inherits NSObject for KVC.

  • I ignored the simplified optional cases.

  • Recursively generate a dictionary or object.

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)

Translated by gpt-3.5-turbo