繁体   English   中英

在字典中快速搜索键

[英]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)
}

有关更多信息,请查看:

如何从Swift中的字典中获取键的值?

实际上,您的密钥必须是唯一的,并且在您的情况下, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM