【问题标题】:Check NSArray contain NSDictionary key in Swift?检查 NSArray 是否包含 Swift 中的 NSDictionary 键?
【发布时间】:2016-02-19 03:28:51
【问题描述】:

我有 NSDictionary 数组,我想检查 NSArray 中是否存在特定的 NSDictionary“键”。

我试过了

if let val = dict["key"] {
    if let x = val {
        println(x)
    } else {
        println("value is nil")
    }
} else {
    println("key is not present in dict")
}

let arrayOfKeys = dictionary.allKeys
if (arrayOfKeys.containsObject(yourKey)) {

}
else {
}

但这是针对单个数组对象的。还有

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

此方法适用于单个 NSDictionary,不适用于 NSArray。

还有

if readArray.contains(["A":1]) {                  ALToastView.toastInView(UIApplication.sharedApplication().keyWindow, withText: "Already added")
      }else{
           readArray.append(["A":0]
       }

如果更改键“A”的值,此代码将在数组中再次添加相同的键

例如。我的数组包含字典[“A”:1],我想检查键“A”是否存在? 如何检查数组中存在的任何键?我需要迭代数组吗?提前致谢。

【问题讨论】:

    标签: ios swift nsarray nsdictionary


    【解决方案1】:

    参考下面的例子:

    var array = [[String:Any]]()
    
    array.append(["key1":"value1"])
    array.append(["key2":"value2"])
    array.append(["key3":"value3"])
    array.append(["key4":"value4"])
    array.append(["key5":"value5"])
    
    let key = "key5"
    
    if let index = (array.indexOf { (dict) -> Bool in
        dict[key] != nil
    })
    {
        print("Key Found at = \(index) ")
    } else {
        print("Key not Found")
    }
    

    【讨论】:

    • 他们的答案是否包含所有关键?
    【解决方案2】:

    您可以使用此方法。基本上,您遍历 dict 数组,获取其索引和 dict 的元组,如果 dict 包含将索引存储在数组中的键。

    let arrayOfDict = [
    ["key1":"value1", "key2":"value2"],
    ["key3":"value3", "key4":"value4", "key5":"value5"],
    ["key6":"value6", "key7":"value7", "key8":"value8"],
    ["key6":"value6", "key7":"value7", "key8":"value8"]
    ];
    
    let keyToCheck = "key6"
    var foundIndex = [Int]()
    for (index, dict) in arrayOfDict.enumerate()
    {
        if let item = dict[keyToCheck] {
                foundIndex.append(index)
        }
    }
    if foundIndex.count > 0 {
        print("Found at \(foundIndex)")
    } else {
        print ("not found")
    }
    

    【讨论】:

      【解决方案3】:

      如果要获取包含键和索引的字典,也可以使用此方法。

      let newArray = arrayOfDict.enumerate().filter { (tuple:(index: Int, element: Dictionary<String, String>)) -> Bool in
          if tuple.element.keys.contains(keyToCheck) {
              return true
          } else  {
              return false
          }
      }
      

      newArray 将是一个类型为 (Int:[String:String]) 的元组数组,其中 tuple.0 将是索引,tuple.1 将是字典

      【讨论】:

        猜你喜欢
        • 2011-07-28
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 2011-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        相关资源
        最近更新 更多