Ala*_*lan 1 dictionary filter swift
我是 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]
Run Code Online (Sandbox Code Playgroud)
使用这个特定的 searchText,我试图得到:
filteredDictionary = ["a": ["aberration"]]
Run Code Online (Sandbox Code Playgroud)
编辑:我希望字典以第一个字母作为键返回,并且值与 searchText 匹配。对不起,如果我不清楚。
这是我尝试过的一些代码,但显然,我无法让它工作:
filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。谢谢。
这是一个基于搜索映射值然后过滤掉空结果的解决方案。
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)
Run Code Online (Sandbox Code Playgroud)
输出:
["a": ["像差"]]
| 归档时间: |
|
| 查看次数: |
4227 次 |
| 最近记录: |