首页 文章

Swift:使用Array作为值过滤字典

提问于
浏览
1

我是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 回答

  • 2

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

    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”:[“像差”]]

  • 0

    试试这个:

    var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
        var searchText = "aberration"
        var filteredDictionary = dictionary.filter { (key, value) -> Bool in
                return (value as! [String]).contains(searchText)
            }.mapValues { (values) -> [String] in
                return [searchText]
            }
        print(filteredDictionary)
    

    您可以使用 filtermap 的组合来获得所需的结果 .

    Output:

    ["a": ["aberration"]]
    
  • 0
    let firstLetter = String(searchText[searchText.startIndex])
    let filteredDictionary = dictionary
        .reduce(into: [String: [String]]()) { (result, object) in
            if object.key == firstLetter {
                let array = object.value.filter({ $0.hasPrefix(searchText) })
                if array.count > 0 {
                    result[object.key] = array
                }
            }
        }
    

    输出:

    [“a”:[“像差”]]

相关问题