Reputation: 3561
How could I accomplish this in swift.
let thing1 = whatever //instance property on class
let index = 1
var myThing = self["thing\(index)"] //does not work
Upvotes: 0
Views: 679
Reputation: 36305
If your class complies to NSObject you can use this:
class Obj : NSObject {
var a1 = "Hi"
}
let obj = Obj()
let ctr = 1
println (obj.valueForKey("a\(ctr)"))
To list the available properties you can use the following (from another SO question):
var count : UInt32 = 0
let classToInspect = Obj.self
let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count)
var propertyNames : [String] = []
let intCount = Int(count)
for var i = 0; i < intCount; i++ {
let property : objc_property_t = properties[i]
let propertyName = NSString(UTF8String: property_getName(property))!
propertyNames.append(propertyName)
}
free(properties)
println(propertyNames)
Upvotes: 1