swift - Searching in Array of Dictionaries -


i'm trying search values in array of dictionaries json. have tableviewcontroller uisearchresultsupdating. found example array of strings:

    func updatesearchresultsforsearchcontroller(searchcontroller: uisearchcontroller) {     filteredtabledata.removeall(keepcapacity: false)     let searchpredicate = nspredicate(format: "self contains[c] %@", searchcontroller.searchbar.text)     let array = tabledata.filteredarrayusingpredicate(searchpredicate)     filteredtabledata = array as! [string]      self.tableview.reloaddata() } 

and don't know how made search in array this:

(     {     id = 3;     name = testnewyork;     },     {     id = 2;     name = testla;     },     {     id = 1;     name = testwashington;     } ) 

my tabledata = [] , filteredtabledata must array too

please, help!

you can use simple filter function this...

tabledata : [[string : string]] = ... // json array of string, string dictionaries...  filteredtabledata = tabledata.filter{     dictionary in     return dictionary["name"] == filterstring } 

something anyway, not written swift while.

you can wrap in function too...

func filter(array : [[string : string]], bystring filterstring : string) -> [[string : string]] {     return array.filter{         dictionary in         return dictionary["name"] == filterstring     } } 

or something. not checked code yet. if doesn't work.

checked in playground , works...

enter image description here

update

changed this...

let data = [     [         "id" : 3,         "name" : "a"     ],     [         "id" : 4,         "name" : "b"     ],     [         "id" : 5,         "name" : "c"     ] ]  let filtereddata = data.filter{     return $0["name"] == "b" } 

and works. can't work out how wrap in function.

if want match beginning of words...

let data = [     [         "id" : 3,         "name" : "hello"     ],     [         "id" : 4,         "name" : "goodbye"     ],     [         "id" : 5,         "name" : "everybody"     ] ]  let filtereddata = data.filter{     let string = $0["name"] as! string      return string.hasprefix("goo") } 

if want contains need find in string.

again, i'm not lying here. i'm running in playground check...

for contains search can this...

let filtereddata = data.filter{     let string = $0["name"] as! string      return string.rangeofstring("db") != nil } 

enter image description here


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -