我是Swift编程的新手 . 对于我的特定项目,我试图用一些用户输入过滤字典,字典的值由一个数组组成 .
这是一些示例代码,以及我要完成的任务:
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,我试图得到:
filteredDictionary = ["a": ["aberration"]]
编辑:我希望字典返回时以第一个字母为键,以及与searchText匹配的值 . 对不起,如果我不清楚 .
这是我尝试过的一些代码,但很明显,我无法让它工作:
filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}
任何帮助,将不胜感激 . 谢谢 .
3 回答
这是一个基于搜索映射值的解决方案,然后过滤掉空结果 .
输出:
试试这个:
您可以使用 filter 和 map 的组合来获得所需的结果 .
Output:
输出: