Pet*_*ert 0 xcode nsdictionary uisearchbar ios swift
我需要通过过滤数组来更改我的搜索功能:
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
}
}
Run Code Online (Sandbox Code Playgroud)
过滤包含符号及其相应名称的字典。理想情况下,我希望能够同时搜索键和值,例如,字典 (CGCoins.shared.coinDictionary) 如下所示:
["btc":"bitcoin","eth":"ethereum","ltc":"litecoin"...]
Run Code Online (Sandbox Code Playgroud)
所以我希望能够使用 UISearchBar 进行搜索,并且能够搜索“btc”并返回“bitcoin”或搜索“bitcoin”并返回“bitcoin”。
我试过这个:
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
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
无法将“[String : String]”类型的值分配给“[String]”类型
我怎样才能成功地为键和值过滤字典,并返回搜索到的任何内容的值?也欢迎任何替代解决方案。
过滤字典会返回一个元组,您需要映射结果并返回字典值。在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
391 次 |
| 最近记录: |