[英]searching keys in dictionary swift
我想在字典中搜索密鑰ID 。 我有一本這樣的字典:
var tableData:[String:Any] = ["id":["path":"","type":"","parameters":[]]]
表格數據有307個項目,並且所有id都是唯一的。 我想搜索字典鍵id ,就像我寫“ get”一樣 ,它需要在表視圖中顯示所有帶有“ get”的搜索結果。
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text
if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchString) }) {
print(entry)
} else {
print("no match")
}
tableView.reloadData()
}
func didChangeSearchText(searchText: String) {
if let entry = tableData.keys.first(where: { $0.lowercased().contains(searchText) }) {
print(entry)
} else {
print("no match")
}
// Reload the tableview.
tableView.reloadData()
}
當我嘗試搜索單詞時,它在調試中顯示“ no match” ,無法讀取條目值寫入的數據。 先感謝您!
要使用鍵訪問字典中的元素,請使用以下代碼。
if let entry = tableData[searchText] {
print(entry)
}
有關更多信息,請查看:
實際上,您的密鑰必須是唯一的,並且在您的情況下, id
是頂級密鑰,您無需執行過濾即可訪問其值。 只需使用tableData[searchText]
即可獲取其值。
如果您不知道id
值,並且想遍歷所有鍵,可以這樣做
for key in tableData.keys {
print(key)
let value = tableData[key]
// or do whatever else you want with your key value
}
根據您已經擁有的內容,您需要執行以下操作
var tableData:[String:Any] = ["hello world":["path":"fgh","type":"dfghgfh","parameters":[]], "something else":["path":"sdfsdfsdf","type":"dfghfghfg","parameters":[]]]
if let entry = tableData.keys.first(where: { $0.lowercased().contains("hello") }) {
print(entry)
// prints 'hello world'
} else {
print("no match")
}
或者您可以簡單地從數據源中獲取一個新的過濾數組,例如
let result = tableData.filter { (key, value) in
key.lowercased().contains("else") // your search text replaces 'else'
}
/*
* result would be an array with the objects based on your id search
* so you'll not only have the keys but the entire object as well
*/
print("Found \(result.count) matches")
嘗試直接在tableData
上使用first(where:)
,如下所示:
func updateSearchResults(for searchController: UISearchController) {
guard let searchString = searchController.searchBar.text else { return }
if let (id, entry) = tableData.first(where: { (key, value) -> Bool in key.lowercased().contains(searchString) }) {
print(entry)
} else {
print("no match")
}
tableView.reloadData()
}
func didChangeSearchText(searchText: String) {
if let (id, entry) = tableData.first(where: { (key, value) -> Bool in key.lowercased().contains(searchText) }) {
print(entry)
} else {
print("no match")
}
// Reload the tableview.
tableView.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.