【问题标题】:Swift dictionary: return values for all keys containing a prefixSwift字典:返回包含前缀的所有键的值
【发布时间】:2022-08-21 03:14:52
【问题描述】:

我有一本字典(Swift 5)

dict = [\"ken\" : 0, \"Kendall\" : 1, \"kenny\" : 2, \"Sam\" : 0, \"Ben\" : 3]

我正在尝试构建一个搜索函数,该函数返回包含前缀的所有键/名称的值

因此,如果输入是 \"ken\",它应该返回键/名称 \"ken\"、\"Kendall\" 和 \"Kenny\" 的值,因为它们的第一个都包含 \"ken\" 3个字符。

func search( string : String, dict : [String:Int] )->[Int] { }

返回[0,1,2]

  • 你看过这个吗:stackoverflow.com/a/41386238/13129471
  • 不,我没有,但我认为解决方案可能包含在其中。谢谢
  • 请添加您解决此问题的尝试。
  • 我刚刚添加了解决方案。我们应该使用过滤器
  • 一种方法是dict.compactMap { $0.key.localizedStandardContains(string) ? $0.value : nil }

标签: swift dictionary search key


【解决方案1】:
let dict = ["ken" : 0, "Kendall" : 1, "kenny" : 2, "Sam" : 0, "Ben" : 3]

let result = dict.filter( { $0.key.lowercased().hasPrefix("ken") } ).values

【讨论】:

    【解决方案2】:

    这就是答案:我们过滤包含输入的键的字典并返回所有值

    func search( string : String, dict : [String:Int] )->[Int] {
    
    let temp = dict.filter { key , value in
            
    return key.contains(string)
    
    }
        
    
    return Array(temp.values)
    }
    

    【讨论】:

    • 这不会返回预期的结果。
    • 确实如此,只是没有特定的顺序
    • 0 和 2 不是预期的结果,根据您自己的规范,它是 0,1,2。
    猜你喜欢
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2020-05-10
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    相关资源
    最近更新 更多