Halfway last month, Erica Sadun wrote a blog entry where she used the reflect() function: Swift: Just because
She just gave the code and didn't comment any further so below, I've liberally sprinkled the code with comments:
// Define a struct to represent a point struct Pt { let x: Int let y: Int init(_ x: Int, _ y: Int) {self.x = x; self.y = y} init(){self.init(0, 0)} }
// Declare an instance of Pt let p = Pt(2, 3)
// Any means: any reference (i.e. class) or value type (i.e. struct, number, etc) // So this function will take an item that can be basically anything in Swift // and look through the names of its members to see if the string matches. func valueForKey(item : Any, key: String) -> Any? {
// The built-in Swift reflect() function is used by Xcode to aid in debugging let mirror = reflect(item) // It returns an array, walk through it for index in 0..<mirror.count { // Each item in the array has a member called 0 and 1 // This assignment is only there for readability's sake let child = mirror[index] // The .0 member is a string and it holds the name of our struct member if key == child.0 { // The .1 member holds information about our struct member // If it's not an optional, return its value with the .value property return child.1.value } } return nil }
// Try it out valueForKey(p, "x")
Instead of using the valueForKey() function, you can also open a Playground and try out a few things yourself:
let mirror = reflect(p) println(mirror[0]) println(mirror[0].0) println(mirror[0].1) println(mirror[0].1.value)