【问题标题】:Using filter to find key in array Swift 3 [duplicate]使用过滤器在数组Swift 3中查找键[重复]
【发布时间】:2017-04-21 09:07:28
【问题描述】:

如何使用过滤器等 Swift 函数优化代码? 我想要做的是,无论该键的值在下面的数组中是什么,我都需要找到一个特定的键(如果存在)?

以下方法对我来说很好,但我认为有更好的方法。

let arrDic = [["Key1": "yes"], ["Key2": "no"], ["Key3": "yes"], ["Key4": "Option1, Option2"], ["Key5": "OC1_OPTIONB"], ["Key6": "H1_OPTIONA"]]

for dict in arrDic {
    if dict["Key1"] != nil {
        print(true)
        break
    }
}

【问题讨论】:

  • @Hamish 谢谢,这就是我想要的。
  • 适用于您的案例:if arrDic.contains(where: { $0["Key1"] != nil })
  • @MartinR 在 Hamish 的上述链接中检查了您的答案并得到了它。谢谢

标签: arrays swift


【解决方案1】:

您可以使用contains 的自定义匹配来搜索项目:

if arrDic.contains(where: {(dict) -> Bool in
    return dict["Key1"] != nil
}) {
    print(true)
}

【讨论】:

    【解决方案2】:
    let arrDic = [["Key1": "yes"], ["Key2": "no"], ["Key3": "yes"], ["Key4": "Option1, Option2"], ["Key5": "OC1_OPTIONB"], ["Key6": "H1_OPTIONA"]]
    
    let result = arrDic.filter { $0["Key1"] != nil }.first
    

    对不起,没有注意到意图,然后添加

    print(result != nil)
    

    甚至更短

    let isPresent = arrDic.filter { $0["Key1"] != nil }.isEmpty
    

    甚至

    let isPresent = arrDic.contains { $0["Key1"] != nil }
    

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 1970-01-01
      • 2018-05-05
      • 2018-02-02
      • 2016-06-30
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      相关资源
      最近更新 更多