【问题标题】:Check if dictionary contains value in Swift检查字典是否包含 Swift 中的值
【发布时间】:2016-07-19 06:43:38
【问题描述】:

只是简单的任务。我有一本字典var types = [Int : String](),它像一个空的一样初始化,在一些用户操作之后它会填充数据。根据本词典中的空白或某些特定数据,我启用/禁用 UI 中的按钮。 检查空虚很容易,但是如何检查字典是否包含特定值? 编译器建议我使用谓词占位符:

types.contains(predicate: ((Int, String)) throws -> Bool>)

【问题讨论】:

    标签: swift nsdictionary nspredicate


    【解决方案1】:

    由于您只想检查给定 是否存在,因此您可以将 contains 方法应用于您的字典(给定原生 Swift 字典)的 values 属性,例如 p>

    var types: [Int : String] = [1: "foo", 2: "bar"]
    print(types.values.contains("foo")) // true
    

    正如@njuri: answer 中所述,使用字典的values 属性似乎会产生开销(我自己还没有验证过)w.r.t.只需根据每个 Dictionary 元素的键值元组中的值条目直接检查 contains 谓词。由于 Swift 速度很快,因此这应该不是问题,除非您使用的是庞大的字典。无论如何,如果您想避免使用 values 属性,您可以查看上述答案中给出的替代方案,或者使用另一种替代方案(Dictionary 扩展名),如下所示:

    extension Dictionary where Value: Equatable {
      func containsValue(value : Value) -> Bool {
        return self.contains { $0.1 == value }
      }
    }
    
    types.containsValue("foo") // true
    types.containsValue("baz") // false
    

    【讨论】:

    • @Brian 对不起,我不关注。
    • swift 3 需要额外的值; types.containsValue(value: "foo")
    【解决方案2】:

    我写了一个函数,它在字典上使用contains 方法。

    您的具体情况:

    let dic : [Int : String] = [1 : "a", 2 : "b"]
    
    func dictionary(dict : [Int : String], containsValue value : String)->Bool{
    
      let contains = dict.contains { (_,v) -> Bool in
          return v == value
      }
      return contains
    }
    
    let c = dictionary(dic, containsValue: "c") // false
    let a = dictionary(dic, containsValue: "a") // true
    

    通用:

    extension Dictionary{
      func containsValue<T : Equatable>(value : T)->Bool{
        let contains = self.contains { (k, v) -> Bool in
    
          if let v = v as? T where v == value{
            return true
          }
          return false
        }
        return contains
      }
    }
    

    我已经针对dictionary.values.contains() 测试了这个函数,它的速度大约快了两倍。

    【讨论】:

    • 声明if condition { return true } else { return false }总是可以简化为return condition
    • 即使是Dictionary 扩展也可能会更好。 dictionary 的冗余是可怕的和无用的。打电话yourDicrtionaryInstance.contains(_:)不是更好吗?
    • W.r.t.到最后一个基准测试段落:这是在实际项目中还是在操场上测试的?我很想知道实际项目中的方法之间的性能是否有任何差异,您可以让编译器变得聪明(确保永远不要在操场上执行基准测试)。
    • @LucaD'Alberti 我已经为Dictionary 添加了一个通用扩展,你怎么看?
    • @dfri 我使用 Xcode 进行了性能测试,这意味着代码已编译、运行 10 次并测量了平均执行时间。
    【解决方案3】:

    如果您想检查是否已经包含 ,方法如下:

    if !yourDictionary.values.contains("Zero") {
       yourDictionary[newItemKey] = newItemValue; //addNewItem
    }
    else {
        print("this value already exists");
    }
    

    如果您想检查 key 是否存在,还有这个:

    1. 您可以将项目添加到您的字典中。
    2. 检查项目的密钥是否已经存在
    3. 如果没有,请附加项目或启用按钮。

      //1
      let newItemKey = 0
      let newItemValue = "Zero"
      //2
      let keyExists = yourDictionary[newItemKey] != nil
      //3
      if !keyExists {
          yourDictionary[newItemKey] = newItemValue; //addNewItem
      }
      else {
      print("This key already exists");
      }
      

    【讨论】:

      【解决方案4】:

      字典 getter 返回一个 optional 值。

      let dictionary = ["ben": "says hi"]
      let containsAlpha = dictionary["alpha"] != nil
      let containsBen = dictionary["ben"] != nil
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        • 2011-01-12
        • 2013-03-04
        • 2021-09-26
        • 1970-01-01
        • 2021-05-18
        • 2018-07-24
        相关资源
        最近更新 更多