如何使用UISearchBar过滤NSDictionary?

问题描述 投票:0回答:3

我需要更改我的搜索功能来过滤数组:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    if searchText != "" {

        filteredName = CGCoins.shared.ids.filter {name in
            return   name.lowercased().contains(searchText.lowercased())}
    } else { filteredName = CGCoins.shared.ids

    }
}

过滤包含符号及其对应名称的词典。理想情况下,我希望能够搜索键和值,例如,字典(CGCoins.shared.coinDictionary)如下所示:

["btc":"bitcoin","eth":"ethereum","ltc":"litecoin"...]

所以我希望能够使用UISearchBar搜索并能够搜索“btc”并返回“比特币”或搜索“比特币”并返回“比特币”。

我试过这个:

func filterNewForSearchText(searchText: String, scope: String = "All") {
    if searchText != "" {

        filteredName = CGCoins.shared.coinDictionary.filter {name in
            return   name.key == searchText}
    } else { filteredName = CGCoins.shared.coinDictionary.values

    }
}

但我得到错误:

无法指定类型'[String:String]'的值来键入'[String]'

如何为键和值成功过滤字典,并返回搜索到的值的值?任何替代解决方案也欢迎。

ios swift xcode nsdictionary uisearchbar
3个回答
4
投票

过滤字典会返回一个元组,您需要映射结果并返回字典值。在else部分中,您需要从其值创建一个新数组:

func filterNewForSearchText(searchText: String, scope: String = "All") {
    if !searchText.isEmpty  {
        filteredName = CGCoins.shared.coinDictionary
                           .filter { 
                               $0.key == searchText 

                            // if you need to search key and value and include partial matches
                            // $0.key.contains(searchText) || $0.value.contains(searchText)

                            // if you need to search caseInsensitively key and value and include partial matches
                            // $0.key.range(of: searchText, options: .caseInsensitive) != nil || $0.value.range(of: searchText, options: .caseInsensitive) != nil
                            }
                           .map{ $0.value }
    } else {
        filteredName = Array(CGCoins.shared.coinDictionary.values)
    }
}

0
投票

尝试这个它正在工作

对于Like Query(String包含另一个字符串)

let data = ["btc":"bitcoin","eth":"ethereum","ltc":"litecoin"]

let filtered = data.filter { $0.key.contains("c") || $0.value.contains("c") }
print(filtered) // ["btc":"bitcoin","ltc":"litecoin"]

用于精确匹配的字符串

let filtered = data.filter { $0.key == "btc"  || $0.value == "litecoin" }

0
投票

错误消息来自于过滤字典不会自动返回其值,但您必须获取其密钥然后将它们包装在数组中:

以下内容在键中查找完全匹配,或者searchText包含在值中:

if searchText != "" {
    filteredName = Array(CGCoins.shared.coinDictionary.filter {name in
        return name.key == searchText || name.value.lowercased().contains(searchText.lowercased())
        }.values)
} else {
    filteredName = Array(CGCoins.shared.coinDictionary.values)
}
© www.soinside.com 2019 - 2024. All rights reserved.