搜索栏字典数组 Swift
Searchbar an array of Dictionaries Swift
我有点卡住了。 简化,我的任务是将 JSON 解析为(例如)UITableView 并通过本机 SearchBar 对其进行过滤。
JSON 看起来像这样:
{
"title":"Two",
"image":"Two.png"
}
...等等
解析后我得到一个字典数组,看起来像这样(分解后有更深入的理解)
imagesArray = [["title":"Two", "image":"Two.png"],["title":"Three Four", "image":"ThreeFour.png"],["title":"Five", "image":"Five.png"]]
我必须使用 "title" 名称进行过滤。 虽然,我无法真正弄清楚如何通过 Dicts 数组使用本机 SearchBar 过滤,但我知道有一些方法。
或者,如果我对字典数组进行解析的整个概念是错误的,请随时纠正我并展示任何不同的方法:(
谢谢!
您可以将 JSON 解析为字典数组,但是,我建议将数据解析为可编码结构数组或像这样 类。
let json = """
[
{
"title":"Two",
"image":"Two.png"
}
]
"""
struct Item: Codable {
var title, image: String
}
if let jsonData = json.data(using: .utf8) {
do {
var items = try JSONDecoder().decode([Item].self, from: jsonData)
} catch {
print("Error: " + error.localizedDescription)
}
}
class del: NSObject,UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
}
}
一旦你有了对象数组,你就可以将它们过滤到一个新数组中,你可以像这样在 textDidChange UISearchBarDelegate 方法中用作 UITableView 的数据。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let filteredItems = items.filter { (item) in
item.title
.lowercased()
.contains(searchText.lowercased())
}
}
希望对您有所帮助。
func searchFor(_ chars: String) -> [[String : String]] {
return imagesArray.filter { ([=10=]["title"]?.range(of: chars, options: .caseInsensitive) != nil) }
}
print(searchFor("th")) // [["title": "Three Four", "image": "ThreeFour.png"]]