我怎么能在swift中完成这个。
let thing1 = whatever //instance property on class
let index = 1
var myThing = self["thing\(index)"] //does not work
答案 0 :(得分:1)
如果你的课程符合NSObject,你可以使用:
class Obj : NSObject {
var a1 = "Hi"
}
let obj = Obj()
let ctr = 1
println (obj.valueForKey("a\(ctr)"))
要列出可用的属性,您可以使用以下内容(来自另一个SO问题):
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)