Swift:以数组为值过滤字典

标签 swift dictionary filter

我是 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) }}

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

这是一个基于搜索映射值然后过滤掉空结果的解决方案。

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": ["aberration"]]

关于Swift:以数组为值过滤字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48089253/

相关文章:

c# - JSON 字符串到 C# 中的模型/HashMap/字典

python - 如何在 pandas 数据框中找到 row_x 的 col1 值 == row_y 的 col2 值的行?

objective-c - 以编程方式唤醒 OSX 上的显示

Python:在列表中嵌入的字典中搜索

python - 为什么按顺序将键插入 python dict 比无序插入更快

javascript - 具有多个值的键上的 lodash 过滤器

forms - ExtJS 表单发送了两次

ios - 通过带字幕的 URL 方案流式传输到 iOS 版 VLC

swift - 如何在另一个 UIViewController 中显示使用 Firebase 登录的用户名

iOS( swift ): UITextField is **not** first responder after becomeFirstResponder method is called?