简体   繁体   中英

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

class A {
  var x = 1
}

var a = A()

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM