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

时间:2016-02-16 11:47:38

标签: ios arrays iphone swift dictionary

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

{
    1455201094707 =     {
    };
    1455201116404 =     {
    }: 
    1455201287530 =     {
    };
}

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

for let tempDict in dataDictionary
{
     self.tempArray.addObject(tempDict)
}
  

错误“让模式无法嵌套在已经不可变的内容中   上下文中,“

for tempDict in dataDictionary as! NSMutableDictionary
{
     self.tempArray.addObject(tempDict)
}
  

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

for tempDict in dataDictionary as! NSMutableDictionary
{
     self.tempArray.addObject(tempDict as! AnyObject)
}
  

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

for tempDict in dataDictionary
{
     self.tempArray.addObject(tempDict)
}
  

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

修改

我希望最终的数组为:

(
  {
    1455201094707 =     {
    };
  }
  {
     1455201116404 =     {
     }:
  } 
)   

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

任何帮助都将受到赞赏.....

我使用过代码:

var tempArray:[NSDictionary] = []

    for (key, value) in tempDict {
        tempArray.append([key : value])
    }
  

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

代码:

let tempArray = tempDict.map({ [$0.0 : $0.1] }) 
  

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

2 个答案:

答案 0 :(得分:5)

首先,当你使用

for let tempDict in dataDictionary {
     self.tempArray.addObject(tempDict)
}

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

所以你应该像这样迭代

for (key, value) in sourceDict {
     tempArray.append(value)
}

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

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

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)
}

答案 1 :(得分:-2)

  1. 从字典中获取所有密钥,因为NSDictionary具有属性allKeys

  2. 循环所有键,并将键的对象添加到数组中。

  3. 在执行上述所有步骤之前,请先阅读documentation

  4. 祝你好运!