Reputation: 37
class A {
var x = 1
}
var a = A()
How to get a variable "x" from object "a" using string name ( a["x"] )?
Upvotes: 3
Views: 4756
Reputation: 350
Expanding on gregheo's answer, if you want to use the subscript syntax like the example in your question, you can do so by implementing 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"])
Upvotes: 2
Reputation: 4270
This will work if the class inherits from NSObject
, where you can use valueForKey:
to get at the properties.
import Foundation
class A: NSObject {
var x = 1
}
let a = A()
let aval = a.valueForKey("x")
println("\(aval)")
Note that aval
is an AnyObject?
here since there's no type information. You'll need to cast it or test what it is yourself.
Upvotes: 4