Swift 检查变量是否已计算或存储
在我的应用程序中,我将自定义类中的对象转换为字典,以便它们可以本地保存在plist和服务器上。我使用以下方法将类的属性转换为字典:Swift 检查变量是否已计算或存储,swift,computed-properties,Swift,Computed Properties,在我的应用程序中,我将自定义类中的对象转换为字典,以便它们可以本地保存在plist和服务器上。我使用以下方法将类的属性转换为字典: func dictionary() -> [String : Any] { var count: UInt32 = 0; let myClass: AnyClass = self.classForCoder; let properties = class_copyPropertyList(myClass, &count);
func dictionary() -> [String : Any] {
var count: UInt32 = 0;
let myClass: AnyClass = self.classForCoder;
let properties = class_copyPropertyList(myClass, &count);
var dictionaryRepresentation: [String:Any] = [:]
for i in 0..<count {
let property = properties![Int(i)]
let cStringKey = property_getName(property);
let key = String(cString: cStringKey!)
dictionaryRepresentation[key] = self.value(forKey: key) as Any
}
return dictionaryRepresentation
}
func dictionary()->[字符串:任意]{
变量计数:UInt32=0;
让myClass:AnyClass=self.classForCoder;
let properties=class\u copyPropertyList(myClass和计数);
var dictionaryRepresentation:[字符串:任意]=[:]
对于0中的i..您可以尝试属性\u copyAttributeList(\u:\ u:)
函数,它可能包含swift计算属性的只读标记。虽然我猜让
属性也有该标记,所以您必须找到一种方法来区分它们。根据dasblinkenlight
的建议,下面是一个可行的解决方案
不要使用上面概述的Objective-C方法,而是创建一个类的镜像
,该类的子类
由所有可设置属性组成,因此不包括可计算属性
这样使用:
let mirror = Mirror(reflecting: MyObject)
for case let (label?, value) in mirror.children {
print (label, value)
}
这里label是变量的名称,value显然是值
编辑:如果有人想将对象转换为字典,我也会在这里发布完整的代码。但是请记住,如果值也是自定义对象,那么这些值也需要转换
func dictionary() -> [String:Any] {
let mirror = Mirror(reflecting: self)
var dictionaryRepresentation = [String:Any]()
for case let (label, value) in mirror.children {
guard let key = label else { continue }
dictionaryRepresentation[key] = value
}
return dictionaryRepresentation
}
。您将无法区分存储属性和计算属性,但通过区分可设置属性和只读属性,您将非常接近。这就足够了,但通读之后,我不确定如何区分。我必须仔细查看。无论如何,感谢您的建议,它看起来很有希望ng.看起来Mirror只是忽略了计算属性,所以这就是区别的方法,只需遍历所有的子项,它们都是可设置的。谢谢!你刚刚超过了我,当我的internet停止工作时,我已经把它写出来了,所以现在就发布它。请看可编码的,而不是反射(在Xcode 9中).它功能更强大,并且只自动编码存储的属性。