收到错误消息
无法转换类型为"不安全的可变指针
?(又名"可选<不安全的可变指针>")到指定类型"不安全的可变指针<objc_property_t?>"(又名"不安全的可变指针<可选><不透明指针>>")不透明指针>可选>不安全的可变指针>
在这一行上
let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)
完整代码在这里
var count = UInt32()
let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)
var propertyNames = [String]()
let intCount = Int(count)
for i in 0..<intCount {
let property : objc_property_t = properties[i]!
guard let propertyName = NSString(utf8String: property_getName(property)) as? String else {
debugPrint("Couldn't unwrap property name for (property)")
break
}
propertyNames.append(propertyName)
}
您收到错误是因为class_copyPropertyList
的返回类型不是UnsafeMutablePointer<objc_property_t?>
。
您的行应为:
let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(self.classForCoder, &count)
class_copyPropertyList()
返回UnsafeMutablePointer<objc_property_t>?
而不是UnsafeMutablePointer<objc_property_t?>
。 通常最好避免显式类型注释,而只写
let properties = class_copyPropertyList(self.classForCoder, &count)
并让编译器推断类型。然后必须解开可选包,例如使用guard
:
guard let properties = class_copyPropertyList(self.classForCoder, &count) else {
return // Handle error ...
}
SwiftString
的创建也可以简化,从而导致
var count = UInt32()
guard let properties = class_copyPropertyList(self.classForCoder, &count) else {
return
}
var propertyNames = [String]()
for i in 0..<Int(count) {
let propertyName = String(cString: property_getName(properties[i]))
propertyNames.append(propertyName)
}
您可以删除类型注释,如下所示:
var count = UInt32()
let properties = class_copyPropertyList(self.classForCoder, &count)
现在还可以映射属性:
if let properties = class_copyPropertyList(self.classForCoder, &count) {
let range = 0..<Int(count)
let names = range.map {
String(cString: property_getName(properties[$0]))
}
}