0

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
nwales
  • 3,521
  • 2
  • 25
  • 47
  • In swift the effect of assignment can be different. I recommend that you read this: https://developer.apple.com/swift/blog/?id=10 – Sinisa Drpa Jan 20 '15 at 19:28

1 Answers1

1

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)
qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • I notice that if the valueForKey() meathod calls for a property that does not exist the app crashes. Since it returns an optional value, is there no way for that to fail silently? – nwales Jan 20 '15 at 19:46
  • I found the following on SO: http://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift – qwerty_so Jan 20 '15 at 20:59