Alex Crow
Alex Crow

Reputation: 439

Searching in Array of Dictionaries

I'm trying to search values in array of dictionaries which I get from JSON. I have a tableViewController with UISearchResultsUpdating. I found an example with 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 I really don't know how to made search in array like this:

(
    {
    id = 3;
    name = TestNewYork;
    },
    {
    id = 2;
    name = TestLA;
    },
    {
    id = 1;
    name = TestWashington;
    }
)

my tableData = [] and filteredTableData must be an array too

Please, help!

Upvotes: 1

Views: 4343

Answers (1)

Fogmeister
Fogmeister

Reputation: 77661

You can use a simple filter function to do this...

tableData : [[String : String]] = ... // your JSON array of String, String dictionaries...

filteredTableData = tableData.filter{
    dictionary in
    return dictionary["name"] == filterString
}

Something like that anyway, not written Swift for a while.

You can wrap it in a 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 the code yet. Will be back if it doesn't work.

Checked in Playground and this works...

enter image description here

UPDATE

Changed to this...

let data = [
    [
        "id" : 3,
        "name" : "a"
    ],
    [
        "id" : 4,
        "name" : "b"
    ],
    [
        "id" : 5,
        "name" : "c"
    ]
]

let filteredData = data.filter{
    return $0["name"] == "b"
}

And it works. Just can't work out how to wrap in a function.

If you want to match the 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 you want a contains you just need to do a find in the string.

Again, I'm not lying here. I'm running it in a Playground to check...

For a contains search you can do this...

let filteredData = data.filter{
    let string = $0["name"] as! String

    return string.rangeOfString("db") != nil
}

enter image description here

Upvotes: 6

Related Questions