[英]Check NSArray contain NSDictionary key in Swift?
I have array of NSDictionary and i want check particular NSDictionary "key" present in NSArray or not. 我有NSDictionary数组,我想检查是否存在于NSArray中的特定NSDictionary“ key”。
I tried 我试过了
if let val = dict["key"] {
if let x = val {
println(x)
} else {
println("value is nil")
}
} else {
println("key is not present in dict")
}
and 和
let arrayOfKeys = dictionary.allKeys
if (arrayOfKeys.containsObject(yourKey)) {
}
else {
}
but this is for individual array object. 但这是针对单个数组对象的。 Also
也
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
This method for individual NSDictionary not for NSArray. 此方法适用于单个NSDictionary,不适用于NSArray。
Also 也
if readArray.contains(["A":1]) { ALToastView.toastInView(UIApplication.sharedApplication().keyWindow, withText: "Already added")
}else{
readArray.append(["A":0]
}
This code will add again same key in array if change value for key "A" 如果更改键“ A”的值,此代码将在数组中再次添加相同的键
Ex. 例如 My array contain dictionary ["A":1] and i want to check key "A" is present or not?
我的数组包含字典[“ A”:1],我想检查键“ A”是否存在? How do i check any key present in Array?
如何检查Array中存在的任何键? Do i need to iterate array?
我需要迭代数组吗? Thanks in advance.
提前致谢。
Refer following example : 请参考以下示例:
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")
}
You can use this method. 您可以使用此方法。 Basically you iterate thru the array of dict getting a tuple of its index and dict and if the dict contains the key you store the index in an array.
基本上,您遍历字典数组以获取其索引和字典的元组,如果字典包含键,则将索引存储在数组中。
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")
}
You can also use this method if you want to get the dictionaries that contains the keys along with the index. 如果要获取包含键和索引的字典,也可以使用此方法。
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
}
}
The newArray will be an array of tuples of type (Int:[String:String]) wherein the tuple.0 will be the index and tuple.1 will be the dictionary newArray将是类型为(Int:[String:String])的元组的数组,其中tuple.0将是索引,tuple.1将是字典
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.