Skip to content

Instantly share code, notes, and snippets.

@inre
Created August 29, 2014 19:56
Show Gist options
  • Save inre/254d6afcd8754e774dc7 to your computer and use it in GitHub Desktop.
Save inre/254d6afcd8754e774dc7 to your computer and use it in GitHub Desktop.
Try reflections in swift
class Document {
func properties() -> [String] {
var array: [String] = []
var mirror = reflect(self)
for i in 0..<mirror.count {
if mirror[i].0 != "super" {
array.append(mirror[i].0)
}
}
return array
}
func propertyTypeString(name: String) -> String? {
var mirror = reflect(self)
for i in 0..<mirror.count {
if (mirror[i].0 == name) {
var value = mirror[i].1.value
if value is String {
return "String"
}
if value is Int {
return "Int"
}
if value is Float {
return "Float"
}
if value is NSData {
return "NSData"
}
}
}
return nil
}
}
class TestDocument: Document {
var a: Int = 5
var name: String = "test"
var data: NSData = NSData()
}
for name in TestDocument().properties() {
println(TestDocument().propertyTypeString(name))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment