Search code examples
swiftnsarray

swift - Put values of Dictionary inside NSArray into Array


I have an NSArray with dictionaries that look like this:

{
    count = 7;
    week = 4;
}

{
    count = 9;
    week = 5;
}

How do I turn these dictionaries inside the NSArray into two arrays that look like this:

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

I have tried: let array = Array(arrayLiteral: results.valueForKey("month"))

But just get this back

[(
    4,
    5
)]

Thank you


Solution

  • You can use flatMap and conditional cast it to Int to extract your dictionary values as follow:

    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]"