swift - 将Dictionary的值放在NSArray中的Array中

时间:2016-02-07 17:33:46

标签: swift nsarray

我有一个带有字典的NSArray,如下所示:

{
    count = 7;
    week = 4;
}

{
    count = 9;
    week = 5;
}

如何将NSArray中的这些词典转换为两个如下所示的数组:

weeks = [4, 5]
count = [7, 9]

我尝试过:let array = Array(arrayLiteral: results.valueForKey("month"))

但是回来吧

[(
    4,
    5
)]

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用flatMap并将其条件转换为Int以提取字典值,如下所示:

let nsArray = NSArray(array: [["count":7,"week":4],["count":9,"week":5]])

let weeks = nsArray.flatMap{$0["week"] as? Int}
let count = nsArray.flatMap{$0["count"] as? Int}

print(weeks)  // "[4, 5]"
print(count)  // "[7, 9]"