for child in mirror.children { print("\(child.label!) ---- \(child.value)") }
// **** 可以看到属性名和值都已经正常打印 ****
// 其他用法
import UIKit
// **** 开发中使用到 Mirror ****
// **** 1. 对象转换为字典 **** classAnimal{ var name: String? var color: String? privatevar birthday: Date=Date(timeIntervalSince1970: 0) }
classCat: Animal{ var master ="小黑" var like: [String] = ["mouse", "fish"] overrideinit() { super.init() color ="黄色" } funcmapDic(mirror: Mirror) -> [String : Any] { var dic: [String : Any] = [:] for child in mirror.children { // 如果没有 label 就被抛弃 iflet label = child.label { let propertyMirror =Mirror(reflecting: child.value) print(propertyMirror) dic[label] = child.value } } // 添加父类属性 iflet superMirror = mirror.superclassMirror { let superDic = mapDic(mirror: superMirror) for p in superDic { dic[p.key] = p.value } } return dic } }
// Mirror 使用 let cat =Cat() cat.name ="大橘为重" let mirror =Mirror(reflecting: cat) let mirrorDic = cat.mapDic(mirror: mirror) print(mirrorDic)
// **** 转 JSON **** structAddress{ var street: String }
structPerson: CustomJSONProtocol{ var name: String="yangqing" var age: Int=27 var isMale: Bool=true var address: Address? =Address(street: "xizhimen North") var height =1.70 var like: Array= ["eat", "sleep", "play"] var weight: Float=75 varsome: Int? }