in Objective-C, I use the following codes to serialize a custom class for a dictionary that works fine. To be familiar with Swift, porting Objective-C codes to Swift. However, I could not achieve this, how can I do this with Swift?
so I achieve with Objective-C
.h
when I wrote the same code in swift, I could not find the equivalent of [self class] .
class class2dicti : NSObject { class func nsdictionaryFromAClass() -> NSDictionary { let aClass = self.classForCoder var propertiesCount : u_int let propertiesInAClass : objc_property_t = class_copyPropertyList(aClass, &propertiesCount) //return NSDictionary() } }
Update
so far i tried:
let aClass = self.classForCoder var propertiesCount : u_int let propertiesInAClass : objc_property_t = class_copyPropertyList(aClass, &propertiesCount)
and
let aClass : AnyClass! = self.classForCoder()
no success, all the same compiler error "Could not find overload for '__conversion', which takes the provided arguments
Decision
regarding the answers below, I found this solution and it worked. I basically created an extension for my class.
class myClass : NSObject { var propertyOne = "prop One" var propertyTwo = [1, 2, 3] var propertyThree = ["A":1, "B":2, "C":3] } extension myClass { func toDictionary() -> NSDictionary { var aClass : AnyClass? = self.dynamicType var propertiesCount : CUnsignedInt = 0 let propertiesInAClass : UnsafePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount) var propertiesDictionary : NSMutableDictionary = NSMutableDictionary() for var i = 0; i < Int(propertiesCount); i++ { var strKey : NSString? = NSString(CString: property_getName(propertiesInAClass[i]), encoding: NSUTF8StringEncoding) propertiesDictionary.setValue(self.valueForKey(strKey), forKey: strKey) } return propertiesDictionary } }
now this let myclazz = myClass().toDictionary() gives me an NSDictionary. All suggestions are welcome.