Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active October 31, 2015 18:53
Show Gist options
  • Save airspeedswift/3d348515e4357b271c11 to your computer and use it in GitHub Desktop.
Save airspeedswift/3d348515e4357b271c11 to your computer and use it in GitHub Desktop.
Extracting properties using reflect()
struct Properties {
// someday soon these can be private
var _name: String, _nameModificationDate: Int
var _shape: String, _shapeModificationDate: Int
init(name: String, nameModificationDate: Int,
shape: String, shapeModificationDate: Int) {
self._name = name
self._nameModificationDate = nameModificationDate
self._shape = shape
self._shapeModificationDate = shapeModificationDate
}
func name()->String { return _name }
func nameModificationDate()->Int { return _nameModificationDate }
func shape()->String { return _shape }
func shapeModificationDate()->Int { return _shapeModificationDate }
}
let p = Properties(name: "Fred", nameModificationDate: 1, shape: "Bob", shapeModificationDate: 2)
let mirror = reflect(p)
for i in 0..<mirror.count {
let (name, element) = mirror[i]
println("\(name) = \(element.value), type \(element.valueType)")
}
// prints out
// _name = Fred, type Swift.String
// _nameModificationDate = 1, type Swift.Int
// _shape = Bob, type Swift.String
// _shapeModificationDate = 2, type Swift.Int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment