我有很多字典。
>[{"name": "John",
"address":
{"home": "addr1",
"work": "add2"}
},
{"name": "Anu",
"address": {"home": "addr1",
"work": "add2"}
}]
我将其保存为用户默认值-
let personData1 = [“名称”:“约翰”,“地址”:{“家庭”:“ addr1”,“工作”:“ add2”}] as [String:Any] let personData2 = [“名称”:“ Anu”,“地址”:{“ home”:“ addr1”,“ work”:“ add2”}] as [String:Any]
var persons = [personsData, personsData1]
UserDefaults.standard.set(forKey: "persons")
以另一种方法检索它,并根据名称对其进行过滤。 让名称=“ 约翰”
遇到错误
无法使用类型为(((Any?)-> Bool)'的参数列表调用'filter'
这是代码:-
func test () {
let personData1 = ["name": "John", "addresses": ["home":"addr1", "work": "addr2"]] as [String : Any]
let personData2 = ["name": "And", "addresses": ["home":"addr1", "work": "addr2"]] as [String : Any]
let persons = [personData1, personData2]
(UserDefaults.standard.set(persons, forKey: "persons")
print("Saved ----\(UserDefaults.standard.value(forKey: "persons"))")
if let savedPersons = UserDefaults.standard.value(forKey: "persons") {
let namePredicate = NSPredicate(format: "name like %@", name);
var filteredArray: [[String:Any]] = savedPersons.filter { namePredicate.evaluate(with: $0) }
print("names = \(filteredArray)")
}
}
如果我尝试这样过滤-
let filteredArray = savedBrs.filter { $0["name"] == name }
遇到其他错误-
“任何”类型的值没有成员“过滤器”
答案 0 :(得分:1)
使用NSPredicate
let arr = [["name":"Rego","address":["one":"peek","two":"geelo"]],["name":"pppp","address":["one":"peek","two":"geelo"]]]
let neededName = "Rego"
let pre = NSPredicate(format: "name == %@",neededName)
let result = arr.filter { pre.evaluate(with:$0) }
print(result)
没有NSPredicate
let result = arr.filter { $0["name"] as? String == neededName }