Swift / Objective C: How to get value from object by string name

class A {
  var x = 1
}

var a = A()

      

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

+3


source to share


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


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







All Articles