使用谓词的字典过滤器数组 - swift3
Posted
技术标签:
【中文标题】使用谓词的字典过滤器数组 - swift3【英文标题】:Array of dictionary filter using predicate - swift3 【发布时间】:2018-08-13 23:08:47 【问题描述】:我有很多字典。
>["name": "John",
"address":
"home": "addr1",
"work": "add2"
,
"name": "Anu",
"address": "home": "addr1",
"work": "add2"
]
我正在像这样将它保存到用户默认值 -
让 personData1 = ["name": "John", "address": "home": "addr1", "work": "add2"] 作为 [String : Any] 让 personData2 = ["name": "Anu", "address": "home": "addr1", "work": "add2"] as [String : Any]
var persons = [personsData, personsData1]
UserDefaults.standard.set(forKey: "persons")
用另一种方法检索它并根据名称过滤它们。 let name = "约翰"
遇到错误
无法使用“((Any?) -> Bool)”类型的参数列表调用“过滤器”
这里是代码:-
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
得到不同的错误 -
“任何”类型的值没有成员“过滤器”
【问题讨论】:
请在问题中包含过滤数组的代码。 【参考方案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
【讨论】:
我这样声明字典 - 让 arr1: [[String:Any]] = [ ["name":"Rego","address":["one":"peek","two ":"geelo"]],["name":"pppp","address":["one":"peek","two":"geelo"]]] 我们不能使用 Any 吗? 这个声明默认给出 [[String:Any]] 如果我保存然后从用户默认值中检索此值,我会收到错误 -> 类型为“任何?”的值没有成员“过滤器” 阅读时使用 UserDefaults.standard.array(forKey: "persons") 知道了。谢谢!我像正常值一样检索它以上是关于使用谓词的字典过滤器数组 - swift3的主要内容,如果未能解决你的问题,请参考以下文章
我想要 swift3.0 的 NSPredicate 的数组过滤器数组