Swift / Objective C: How to get value from object by string name
2 answers
This will work if the class inherits from NSObject
where you can use valueForKey:
to get properties.
import Foundation
class A: NSObject {
var x = 1
}
let a = A()
let aval = a.valueForKey("x")
println("\(aval)")
Note that aval
here AnyObject?
, as there is no type information. You will need to quit or check what it is.
+4
source to share
Expanding on gregheo's answer , if you want to use substring syntax like the example in your question, you can do so by doing subscript
.
class A: NSObject {
var x = 1
subscript(key: String) -> Int {
get {
return self.valueForKey(key) as Int
}
set {
self.setValue(newValue, forKey: key)
}
}
}
var a = A()
println(a["x"])
a["x"] = 5
println(a["x"])
+2
source to share