gpt4 book ai didi

ios - 我想从数组中的数组中搜索?参见示例

转载 作者:行者123 更新时间:2023-11-29 05:30:55 24 4
gpt4 key购买 nike

我必须从数组内的数组中进行搜索。但我做不到。请参阅数组示例:

[
{
"hospital_name": "Medical Hospital",
"address": "1/127 India ",
"facilities_data": [
{
"name": "Speciality",
"facilities_list": [
{
"facilities_name": "Andrology"
},
{
"facilities_name": "Cosmetology"
}
]
},
{
"name": "Facilities",
"facilities_list": [
{
"facilities_name": "ICU"
},
{
"facilities_name": "Multispeciality"
},
{
"facilities_name": "OPD"
},
{
"facilities_name": "Physical Therapy"
}
]
}
]
}
]

我必须使用医院名称、地址和设施名称进行搜索

我现在正在这样做,我正在获得医院名称和地址的成功结果。 但不适用于设施名称

func getAllSearchedArrayList(txt: String) {
let namePredicate1 = NSPredicate(format: "hospital_name contains[c] %@ || facilities_name contains[c] %@ || address contains[c] %@", txt, txt, txt);
var searchedArray1: Array<Any>!
searchedArray1 = self.hospitalArray.filter { namePredicate1.evaluate(with: $0) };
self.searchedHospitalArray = searchedArray1
if self.searchedHospitalArray.count == 0 {
self.hospitalTableView.reloadData()
}
else {
self.hospitalTableView.reloadData()
}
}

请帮帮我。

最佳答案

将数组构造为如下结构:

    struct Hospital{
let hospital_name : String!
let address : String!
let facilities_Data : [Facilities_Data]!
}

struct Facilities_Data{
let name : String!
let facilities_list : [String]!
}

var hospitals = [Hospital]() // parse your array to struct first
var filteredHospitals = hospitals // use filteredHospitals to fill your tableview data instead of the original hospitals array to keep the original data intact.

func getAllSearchedArrayList(searchText: String){

//reuse original data if no searchText else starts to filter

filteredHospitals = searchText.isEmpty ? hospitals : hospitals.filter({ (hospital) -> Bool in
return hospital.hospital_name.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil || hospital.address.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil || hospital.facilities_Data.contains(where: { (data) -> Bool in
return data.facilities_list.contains(where: { (name) -> Bool in
return name.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
})
})
})
self.tableView.reloadData()
}

这里的主要思想是解决可怕的字典数组问题,并将它们分成更小的代码块和可识别的类型,以便您可以使用该特定类型进行搜索。 (在本例中使用 range(of:) 的字符串。

我个人将其与搜索栏委托(delegate)结合使用: search(_ searchBar: UISearchBar, textDidChange searchText: String) 因为它允许用户每次在搜索栏中输入内容时都可以看到结果,而不是仅仅输入整个字符串看到没有结果,这样tableview就会不断刷新并显示越来越少的结果。

关于ios - 我想从数组中的数组中搜索?参见示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57586992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com