gpt4 book ai didi

Swift:以数组为值过滤字典

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:31 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com