Mirror 是一個 Swift 對象反射類庫,100%用 Swift 編寫,不依賴 Objective-C。
創(chuàng)建一個 Mirror 實例:
struct Person { let name: String var age: Int } var person = Person(name: "Jon", age: 27) let mirror = Mirror(person)獲取 Mirror 實例的信息:
mirror.name //"MirrorTest.Person" mirror.shortName //Person mirror.memorySize // 32 mirror.isClass //false mirror.isStruct //true獲取被反射對象的屬性信息:
mirror.names //["name", "age"] mirror.values //["Jon", 27] mirror.types //[Swift.String, Swift.Int] mirror.typesShortName //["String", "Int"] mirror["name"] //"Jon" mirror["age"] //27 mirror.toDictionary //["age": 27, "name": "Jon"]Mirror 是集合類型,所有的集合類型的方法都可以在 Mirror 中使用, 比如: Iterating, count, map, filter等。
// Iterate over its children MirrorItems for item in mirror { println(item) } //name: Swift.String = Jon //age: Swift.Int = 27 let children = mirror.children //Array of MirrorItem let firstKid = children[0] //{name: "name", type: Swift.String, value: "Jon" } var mirP = mirror[1] mirP.name // "age" mirP.value // 27 mirP.type // Swift.Int