Aloogy Aloogy - 5 months ago 28
iOS Question

Filtering/Searching Nested Struct Array

I'm trying to add a search bar to the top of a grouped table. However I'm unsure how to filter through my data. The data is stored in a nested array with objects held in this format;

struct Group {
var id: String
var type: String
var desc: String
var avatar: String
var name: String

init() {
id = ""
type = ""
desc = ""
avatar = ""
name = ""
}
}


Because I get data from two sources, two arrays are nested together, this also makes it simpler to create the two sections of the grouped table. I'll note, they both use the same Group struct.

self.masterArray = [self.clientArray, self.departmentArray]


This "masterArray" is then used to populate the table. Filtering/searching a single array isn't too difficult, but how do I search through a nested array?

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

}


EDIT:
I've finally got things working, courtesy of @appzYourLife.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("Searching for:" + searchText)
if searchText.isEmpty {
filterArray = masterArray
} else {
filterArray = [ clientArray.filter { $0.name.range(of: searchText) != nil }] + [ departmentArray.filter { $0.name.range(of: searchText) != nil } ]
}
tableView.reloadData()
}

Answer

Given

struct Group {
    let id: String = ""
    let type: String = ""
    let desc: String = ""
    let avatar: String = ""
    let name: String = ""
}

let clients = [Group(), Group(), Group(), Group()]
let departmens = [Group(), Group(), Group(), Group()]

let clientsAndDepartments = [clients, departmens]

You can search inside clients and department writing

let results = (clients + departmens).filter { $0.id == "123" }

enter image description here

Update #1

Now understand that you want to filter both arrays but as result you still want something like this [[Group]].

So here's the code

var filterArray = [clients.filter { $0.name == "White" }] + [departmens.filter { $0.name == "White" }]

Update #2

If you want to search for string inclusione the use this code

var filterArray = [ clients.filter { $0.name.rangeOfString("White") != nil }] + [ departmens.filter { $0.name.rangeOfString("White") != nil } ]