简体   繁体   中英

Having trouble in filter array of dictionaries coming from server in swift

The dictionary coming from server is

{
    data = ({
        email = "a123@gmail.com";
        phone = 9804504884;
        "user_id" = 11;
        username = abcd;
    });
}

var dataArray:NSArray = dict.objectForKey("data") as! NSArray
println("names = ,\(dataArray)");
var pre:NSPredicate = NSPredicate(format: "username CONTAINS[c] a")
var result:NSArray = dataArray.filteredArrayUsingPredicate(pre)
println("names = ,\(result)");

I am always getting result blank result array from this swift code. Please help me to resolve this issue. Thanks

Do it like this,

let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
let predicate = NSPredicate(format: "username CONTAINS[C] 'a'")
if let filteredArray = json["data"]?.filteredArrayUsingPredicate(predicate) {
   // do something with array
}

Note you should wrap your string inside single quotes '' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM