Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 671
Pavel Taran Avatar asked Mar 17 '26 11:03

Pavel Taran


2 Answers

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.

like image 53
gregheo Avatar answered Mar 19 '26 02:03

gregheo


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"])
like image 28
mikedave Avatar answered Mar 19 '26 00:03

mikedave