Filtering dictionary inside an array in Swift

BoSoud picture BoSoud · Jun 8, 2014 · Viewed 9.8k times · Source

I have An Array With Dictionary example :

[{
    "CATEGORYNAME" = "name0";
    "CATEGORYSUBID" = 2;
    "ID" = 1;
}, {
    "CATEGORYNAME" = "name1";
    "CATEGORYSUBID" = 2;
    "ID" = 2;
}, {
    "CATEGORYNAME" = "name2";
    "CATEGORYSUBID" = 0;
    "ID" = 3;
}]

I Used to Filter it in Objective C Like this

JSON_data = [[[Global SharedData]Categorys] filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"(CATEGORYSUBID == %@)", Filter]];

i tried To Use Array Filter but not Succeed

var JSON_data = Global.SharedData().Categorys
JSON_data = JSON_data.filter( ?????

JSON_data is has all data i have print it with Printin

Answer

naz picture naz · Dec 17, 2014

Filtering a dictionary would be simple like below. We filter ages that are below 30.

var visitors = [["age" : 22], ["age" : 41], ["age" : 23], ["age" : 30]]

var filteredVisitors = visitors.filter({
    $0["age"] < 30 //access the value to filter
})

println(filteredVisitors)
//[["age" : 22], ["age" : 23]]

More info here: Filtering a Swift Array of Dictionaries or Object property