Swift51.com
Swift 头像
Swift  2016-05-15 00:10

Swift 对象反射类库 Mirror

回复:0  查看:4196  感兴趣:11  赞:0  

Mirror 是一个 Swift 对象反射类库,100%用 Swift 编写,不依赖 Objective-C。

创建一个 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

相关开源代码