相关疑难解决方法(0)

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)

任何帮助,将不胜感激。谢谢。

dictionary filter swift

1
推荐指数
1
解决办法
4227
查看次数

标签 统计

dictionary ×1

filter ×1

swift ×1