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

标签 ios arrays iphone swift dictionary

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

{
    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/

相关文章:

c# - 使用 Visual Studio 2015 社区开发安全的 Android 和 iOS 应用程序,无需像 Xamarin 这样的第 3 方许可

ios - UIPopoverController 不会初始化 ContentViewController

iphone - 如何扩展我检查 2 张卡是否匹配到 3 张匹配的卡的方法?

python - 在python中将列表转换为二维数组

python - 在numpy中用零填充数组

c++ - 由第二个数组中的值限定的随机数数组

iphone - 另一个 UIViewController 中的 UIViewController 的新实例 : Why can't I set an instance variable?

ios - 如何使用非英文文本在 UITextView 中启用连字符?

iphone - 应用内购买突然无法在 IOS 模拟器中运行

iphone - 核心数据优化