class_copyPropertyList在Swift 5中提供了空属性,并且在Swift 3中工作正常
extension NSObject {
func toDictionary(from classType: NSObject.Type) -> [String: Any] {
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
let propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for i in 0 ..< Int(propertiesCount) {
let property = propertiesInAClass?[i]
let strKey = NSString(utf8String: property_getName(property)) as String?
if let key = strKey {
propertiesDictionary.setValue(self.value(forKey: key), forKey: key)
}
}
return propertiesDictionary as! [String : Any]
}
}
//将其称为NSObject子类
let product = Product()
let dict = product.toDictionary(from: Product.self)
print(dict)