反射(I)

时间:2022-06-30 17:07:16

反射获取属性和属性值

 let item = DoctorGroup()
guard let dic = InterfaceTests.obtainValues(subObject: item) else {
XCTFail("testFetchMyGroups is \(dataIsEmpty)")
return
} for (_, value) in dic {
print("------------>\(value)")
} // 获取Model的属性和值 纯Swift专用
class func obtainValues<T>(subObject: T) -> [String: Any]? {
var resultDic = [String: Any]() let mirror = Mirror(reflecting: subObject)
for (name, value) in mirror.children {
resultDic[name!] = value
} var superMirror: Mirror? = mirror.superclassMirror while superMirror != nil {
for (name, value) in (superMirror?.children)! {
resultDic[name!] = value
}
superMirror = superMirror?.superclassMirror //获取父类的属性和值
}
return resultDic
}