Swift:使用数组作为值过滤字典 [英] Swift: Filter a Dictionary with Array as Value
问题描述
我是Swift编程的新手.对于我的特定项目,我试图用一些用户输入来过滤字典,并且字典的值由一个数组组成.
I'm new to Swift programming. For my particular project, I'm trying to filter a dictionary with some user input, and the dictionary's value consists of an array.
这是一些示例代码,以及我要完成的工作:
Here is some sample code, and what I'm trying to accomplish:
var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
var filteredDictionary = [String: [String]]()
var searchText = "aberration"
//getting the first letter of string
var firstLetter = searchText[searchText.startIndex]
使用这个特定的searchText,我试图获得:
With this particular searchText, I'm trying to get:
filteredDictionary = ["a": ["aberration"]]
我希望字典以第一个字母作为键返回,并与searchText匹配的值返回.抱歉,我不清楚.
I want the dictionary to return with the first letter as its key, and the values with what searchText matches up with. Sorry if it I wasn't clear.
这是我尝试过的一些代码,但是显然,我无法使它正常工作:
Here is some code I have tried, but obviously, I can't get it to work:
filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}
任何帮助将不胜感激.谢谢.
Any help would be appreciated. Thanks.
推荐答案
这是一种解决方案,可以根据搜索结果映射值,然后过滤出空结果.
Here's a solution that maps the values based on the search and then filters out the empty results.
var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
var searchText = "aberration"
let filteredDictionary = dictionary.mapValues { $0.filter { $0.hasPrefix(searchText) } }.filter { !$0.value.isEmpty }
print(filteredDictionary)
输出:
["a":[像差"]]
["a": ["aberration"]]
这篇关于Swift:使用数组作为值过滤字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!