使用字典数据迭代字典并将其添加到swift中的数组中

Ami*_*mit 2 arrays iphone dictionary ios swift

我有一个包含多个字典数据的字典:

{
    1455201094707 =     {
    };
    1455201116404 =     {
    }: 
    1455201287530 =     {
    };
}
Run Code Online (Sandbox Code Playgroud)

我必须将所有这些字典添加到swift中的数组中.如何将字典迭代为:

for let tempDict in dataDictionary
{
     self.tempArray.addObject(tempDict)
}
Run Code Online (Sandbox Code Playgroud)

错误"让模式不能嵌套在已经不可变的上下文中"

for tempDict in dataDictionary as! NSMutableDictionary
{
     self.tempArray.addObject(tempDict)
}
Run Code Online (Sandbox Code Playgroud)

错误:参数类型元素(aka(键:AnyObject,值:AnyObject))参数类型不符合预期类型anyobject

for tempDict in dataDictionary as! NSMutableDictionary
{
     self.tempArray.addObject(tempDict as! AnyObject)
}
Run Code Online (Sandbox Code Playgroud)

错误:无法将类型'(Swift.AnyObject,Swift.AnyObject)'(0x1209dee18)的值转换为'Swift.AnyObject'(0x11d57d018).

for tempDict in dataDictionary
{
     self.tempArray.addObject(tempDict)
}
Run Code Online (Sandbox Code Playgroud)

错误:类型AnyObject的值没有成员生成器

编辑

我希望最终的数组为:

(
  {
    1455201094707 =     {
    };
  }
  {
     1455201116404 =     {
     }:
  } 
)   
Run Code Online (Sandbox Code Playgroud)

实现这个的正确方法是什么?

任何帮助将不胜感激.....

我用过代码:

var tempArray:[NSDictionary] = []

    for (key, value) in tempDict {
        tempArray.append([key : value])
    }
Run Code Online (Sandbox Code Playgroud)

错误:AnyObject类型的值不符合预期的字典键类型NSCopying

代码:

let tempArray = tempDict.map({ [$0.0 : $0.1] }) 
Run Code Online (Sandbox Code Playgroud)

错误:没有更多上下文,表达式类型不明确

Ant*_*sov 5

首先,当你使用时

for let tempDict in dataDictionary {
     self.tempArray.addObject(tempDict)
}
Run Code Online (Sandbox Code Playgroud)

Swift在tempDict中为你提供了类似(键,值)的元组.

所以你应该像这样迭代

for (key, value) in sourceDict {
     tempArray.append(value)
}
Run Code Online (Sandbox Code Playgroud)

注意:我在这里使用原生swift结构,我的建议 - 尽可能经常使用它们(而不是ObjC)

或者你可以在字典上使用map-function.

let array = sourceDict.map({ $0.1 })
Run Code Online (Sandbox Code Playgroud)

编辑.对于

(
  {
    1455201094707 =     {
    };
  }
  {
     1455201116404 =     {
     }:
  } 
) 
Run Code Online (Sandbox Code Playgroud)

使用

for (key, value) in sourceDict {
     tempArray.append([key : value])
}
Run Code Online (Sandbox Code Playgroud)

要么

let array = dict.map({ [$0.0 : $0.1] })
Run Code Online (Sandbox Code Playgroud)

注意.如果您使用NSDictionary,则应将其强制转换为swift Dictionary

if let dict = dict as? [String: AnyObject] {
    let array = dict.map({ [$0.0 : $0.1] })
    print(array)
}
Run Code Online (Sandbox Code Playgroud)