简体   繁体   中英

Array of dictionary filter using predicate - swift3

I have array of dictionaries.

>[{"name": "John",
"address": 
{"home": "addr1", 
"work": "add2"}
},
{"name": "Anu",
"address": {"home": "addr1", 
"work": "add2"}
}]

I am saving it to user default like this -

let personsData1 = ["name": "John", "address": {"home": "addr1", "work": "add2"}] as [String : Any] let personsData2 = ["name": "Anu", "address": {"home": "addr1", "work": "add2"}] as [String : Any]

var persons = [personsData, personsData1]
UserDefaults.standard.set(forKey: "persons") 

Retrieving it in another method and filter them on the basis of name. let name = " John "

Getting below error

Cannot invoke 'filter' with an argument list of type '((Any?) -> Bool)'

Here is the code :-

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)")
    }
}

If I try to filter like this -

let filteredArray = savedBrs.filter { $0["name"] == name }

getting different error -

Value of type 'Any' has no member 'filter'

With 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)

Without NSPredicate

let result = arr.filter { $0["name"] as? String  == neededName }

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