我有一本字典,
var DataDict:[String:[String]] = [String:[String]]()
DataDict[“fruits”] = [“apple”,”orange”,”pineapple”,”grape”]
DataDict[“vehicle”] = [“car”,”cycle / scooter“,”bike”]
DataDict[“colours”] = [“black”,”white”,”yellow”,”green”,”blue”]
所以当我在搜索栏中搜索时,如果searchText
是水果,那么tableview
应该显示完整的水果数组,否则搜索文本匹配到的任何内容DataDict每个键内的单个对象?
那么如何实现这一目标才能显示tableview
。我需要在searchBar
textDidChange 委托中实现它。
Finllay我需要将结果显示为DataDict
对象作为标题,并将其key
作为副标题显示。
例如:
apple
fruits
pineapple
fruits
答案 0 :(得分:1)
你可以这样做,
var DataDict:[String:[String]] = [String:[String]]()
DataDict["fruits"] = ["apple","orange","pineapple","grape"]
DataDict["vehicle"] = ["car","cycle / scooter","bike"]
DataDict["colours"] = ["black","white","yellow","green","blue"]
let filterarray = Array(DataDict.keys).filter { $0.contains("searchText")}
print("\(filterarray)")
for string in filterarray {
print("\(DataDict[string]!)")
}
现在您可以使用filterarray
显示您的要求答案 1 :(得分:1)
try below method for searchingtext. Result can be displayed to table
func searchText(string:String) -> [String] {
let text = string
var DataDict:[String:[String]] = [String:[String]]()
DataDict["fruits"] = ["apple","orange","pineapple","grape"]
DataDict["vehicle"] = ["car","cycle / scooter","bike"]
DataDict["colours"] = ["black","white","yellow","green","blue"]
var searchedItems = [String]()
for key in DataDict.keys {
if text == key {
if let items = DataDict[key] {
searchedItems.removeAll()
searchedItems.append(contentsOf: items)
}
break;
}
else {
if let items = DataDict[key] {
let filterd = items.filter({ (x) -> Bool in
return x.lowercased().contains(text.lowercased())
})
if filterd.count > 0 {
searchedItems.append(contentsOf: filterd)
}
}
}
}
print("SearchedItems: \(searchedItems)")
return searchedItems
}
答案 2 :(得分:1)
你也可以通过这种方式获得阵列以加快响应速度。
let arrTemp = Array(DataDict.keys).filter { $0.contains(searchBar.text!)}
print(DataDict[arrTemp[0]])
希望它对您有用.. :)
答案 3 :(得分:1)
我知道这种情况已经晚了,但是希望通过使用flatMap和过滤器发布一个改进的答案。
dict3 = dict(dict1)
for key1 in dict3:
for key2 in dict2:
dict3[key1].update({"trait4": dict2[key2]["trait4"]})
使用平面地图,您不需要迭代每个字符串数组,因为它会将您的嵌套字典展平为一个。有关flatMap https://medium.com/@abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8的更多信息 希望这会有所帮助。
答案 4 :(得分:0)
创建空数组并将其初始化为 DataDict 的第一个键,并将其设为 tableView 的 dataSource
然后每次搜索都会使用与搜索匹配的新内容替换它的内容并重新加载 tableView