我有一本包含多个字典数据的字典:
{
1455201094707 = {
};
1455201116404 = {
}:
1455201287530 = {
};
}
我必须快速将所有这些字典添加到一个数组中。 如何迭代字典:
for let tempDict in dataDictionary
{
self.tempArray.addObject(tempDict)
}
Error "let pattern cannot appear nested in an already immutable context"
for tempDict in dataDictionary as! NSMutableDictionary
{
self.tempArray.addObject(tempDict)
}
Error : Argument type element(aka(key:AnyObject, value:AnyObject)) argument type does not conform to expected type anyobject
for tempDict in dataDictionary as! NSMutableDictionary
{
self.tempArray.addObject(tempDict as! AnyObject)
}
Error: Could not cast value of type '(Swift.AnyObject, Swift.AnyObject)' (0x1209dee18) to 'Swift.AnyObject' (0x11d57d018).
for tempDict in dataDictionary
{
self.tempArray.addObject(tempDict)
}
Error: Value of Type AnyObject has no member generator
编辑
我希望最终的数组为:
(
{
1455201094707 = {
};
}
{
1455201116404 = {
}:
}
)
实现这个的正确方法是什么?
任何帮助将不胜感激......
我使用了代码:
var tempArray:[NSDictionary] = []
for (key, value) in tempDict {
tempArray.append([key : value])
}
Error: value of type AnyObject does not conform to expected dictionary key type NSCopying
代码:
let tempArray = tempDict.map({ [$0.0 : $0.1] })
Error : type of expression is ambiguous without more context
最佳答案
首先,当你使用时
for let tempDict in dataDictionary {
self.tempArray.addObject(tempDict)
}
Swift 为您提供了 tempDict 中类似 (key, value) 的元组。
所以你应该像这样迭代
for (key, value) in sourceDict {
tempArray.append(value)
}
注意:我在这里使用了原生 swift 结构,我的建议 - 尽可能经常使用它们(而不是 ObjC 结构)
或者您可以在字典上使用映射函数。
let array = sourceDict.map({ $0.1 })
编辑。对于
(
{
1455201094707 = {
};
}
{
1455201116404 = {
}:
}
)
使用
for (key, value) in sourceDict {
tempArray.append([key : value])
}
或
let array = dict.map({ [$0.0 : $0.1] })
注意。如果您使用 NSDictionary,则应将其转换为 swift Dictionary
if let dict = dict as? [String: AnyObject] {
let array = dict.map({ [$0.0 : $0.1] })
print(array)
}
关于ios - 使用字典数据迭代 Dictionary 并将其添加到 swift 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35431754/