反射獲取屬性和屬性值 1 let item = DoctorGroup() 2 guard let dic = InterfaceTests.obtainValues(subObject: item) else { 3 XCTFail("testFetchMyGroups is \(dataIsEm ...
反射獲取屬性和屬性值
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