欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

反射(I)

程序员文章站 2022-04-19 18:18:23
反射获取属性和属性值 1 let item = DoctorGroup() 2 guard let dic = InterfaceTests.obtainValues(subObject: item) else { 3 XCTFail("testFetchMyGroups is \(dataIsEm ......

反射获取属性和属性值

反射(I)
 1 let item = DoctorGroup()
 2 guard let dic = InterfaceTests.obtainValues(subObject: item) else {
 3                             XCTFail("testFetchMyGroups is \(dataIsEmpty)")
 4                             return
 5                         }
 6 
 7 
 8 for (_, value) in dic {
 9                             print("------------>\(value)")
10                         }
11 
12 
13 //    获取Model的属性和值   纯Swift专用
14     class func obtainValues<T>(subObject: T) -> [String: Any]? {
15         var resultDic = [String: Any]()
16         
17         let mirror = Mirror(reflecting: subObject)
18         for (name, value) in mirror.children {
19             resultDic[name!] = value
20         }
21         
22         var superMirror: Mirror? = mirror.superclassMirror
23 
24         while superMirror != nil {
25             for (name, value) in (superMirror?.children)! {
26                 resultDic[name!] = value
27             }
28             superMirror = superMirror?.superclassMirror  //获取父类的属性和值
29         }
30         return resultDic
31     }
View Code