Tycho Pandelaar
Tycho Pandelaar

Reputation: 7525

Need to get instanceName as a String from a var in Swift

Suppose I have the following line of code.

var instanceName = "someString"

How would I get the name of the instance in a String format so I can use that as a key to store the var in NSUserDefaults? So in the above case, I am looking to get "instanceName" from instanceName...

Follow-up question: How do I get back to the variable contents by using a string. E.g. "instanceName"

Upvotes: 3

Views: 1128

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

You can get all variables from class instance by using class_copyIvarList (as I know Swift doesn't support optional vars), loop over them and get names.

var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)   

for var i = 0; i < Int(propertiesCount); i++ {                                
  var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)  
}//for

Playground

class Myclass{

    var myInteger:Int = 1
    var myBoolean:Bool = false
    var myString:String = "heyStr"

    func printValues(){
      var aClass : AnyClass? = self.dynamicType
      var propertiesCount : CUnsignedInt = 0
      let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)        

      for var i = 0; i < Int(propertiesCount); i++ {
        var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)

        println(propName)
     }//for
    }       
}

var mc:Myclass = Myclass()
mc.printValues()

Output:

myInteger
myBoolean
myString

[EDIT 1]

Ivar refers to Objective-C runtime:

/// An opaque type that represents an instance variable.
typealias Ivar = COpaquePointer

[EDIT 2]

If you interesting to get values also do two things:

  • inherit your cass from NSObject a.e. class Myclass:NSObject{..}
  • var propValue : AnyObject! = self.valueForKey(propName)

Btw, if you want to store them into some Dictionary, you need 1st check their type. Because you have propValue defined as AnyObject

Upvotes: 4

Related Questions