在字典swift中搜索键

时间:2017-06-09 07:27:35

标签: ios swift dictionary swift3

我想在字典中搜索密钥 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()
}

当我尝试搜索单词时,它会打印“不匹配”,在调试中,无法读取条目值的数据写入。先感谢您!

3 个答案:

答案 0 :(得分:0)

要使用键访问Dictionary中的元素,请使用以下代码。

if let entry = tableData[searchText] {
   print(entry)
}

有关详细信息,请查看:

how can i get key's value from dictionary in Swift?

答案 1 :(得分:0)

事实上,您的密钥必须是唯一的,因为在您的情况下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")

答案 2 :(得分:0)

尝试直接在first(where:)上使用tableData,如下所示:

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()
}
相关问题