我有一个快速的属性列表(由NSPropertyListSerialization生成),如下所示:
let plist: Dictionary<String,AnyObject>
其中AnyObject
可以是String或其他嵌套Dictionary<String, AnyObject>
或值数组,如下所示:
- key/value
- key/value
- key/dictionary
- key/value
- key/value
- key/dictionary
- key/dictionary
- key/value
- key/value
- key/value
- key/dictionary
- key/value
- key/value
Swift中最容易找到字典中任何给定键的值的方法是什么?
EDIT。我创建了一个这样的递归函数:
// returns value for any given key in the plist
func valueForPlistKey(key: String, parent:Dictionary<String, AnyObject>) -> AnyObject? {
for (akey, avalue) in parent {
if key == akey {
return avalue
} else if avalue is Dictionary<String, AnyObject> {
if let nestedVal = valueForPlistKey(key, parent: avalue as! Dictionary<String, AnyObject>) {
return nestedVal
}
}
}
return nil
}
然而,使事情变得复杂的是嵌套对象可以是字典或数组。除非我需要再考虑一下......