Mirror
用途: 获取到对象的全部属性的key、value。
示例:
点击查看代码
class Person {
private var name: String
private var age: Int
var address: String
var saySomething: String {
return "hello world"
}
init(name: String, age: Int, address: String) {
self.name = name
self.age = age
self.address = address
}
}
class Student: Person {
var stuId: String
private var school = "清华"
var cla: String {
"三年二班"
}
init(name: String, age: Int, address: String, stuId: String) {
self.stuId = stuId
super.init(name: name, age: age, address: address)
}
}
let stu = Student.init(name: "John", age: 30, address: "123 Main St", stuId: "123")
let kvs = Mirror.init(reflecting: stu).children
var result: [String: Any] = [:]
for kv in kvs {
guard let key = kv.label as? String else { continue }
result[key] = kv.value
}
print(result) // 打印结果:["school": "清华", "stuId": "123"]
结论
上述代码中,我们创建了一个Person类以及继承自Person类的Student类,通过Student类创建了一个stu对象,通过最终的打印结果不难发现:
- 继承来的属性不会被Mirror访问到
- Mirror只能访问存储属性,无法访问计算属性
- 属性的访问权限对Mirror没有影响,private修饰的计算属性也会被Mirror反射到