I can't get properties of a Class using swift by class_copyPropertyList
Swit 3 Version
extension NSObject {
// convert to dictionary
func toDictionary(from classType: NSObject.Type) -> [String: Any] {
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
var propertiesDictionary = [String:Any]()
for i in 0 ..< Int(propertiesCount) {
if let property = propertiesInAClass?[i],
let strKey = NSString(utf8String: property_getName(property)) as String? {
propertiesDictionary[strKey] = value(forKey: strKey)
}
}
return propertiesDictionary
}
}
// call this for NSObject subclass
let product = Product()
let dict = product.toDictionary(from: Product.self)
print(dict)
You need to make sure your class subclasses from NSObject, or add @objc in front of your class name (which internally does the same I believe).
The class_copyPropertyList method will only work on NSObject subclasses, which Swift classes don't derive from.