3
class A {
  var x = 1
}

var a = A()

How to get a variable "x" from object "a" using string name ( a["x"] )?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.