在Dictionary - Swift 3中检查nil值

时间:2017-03-17 08:46:45

标签: swift dictionary

我已将XML转换为字典,我想首先检查是否有任何值为nil。

是否有任何替代这个丑陋的代码(字典包含30个键值对):

if (xmlDict["key1" != nil && xmlDict["key2" != nil && .... && xmlDict["key30" != nil) {
     //Do something with these values
} else {
     //Do not do anything at all with this dictionary
}

[更新] 字典具有这种格式(混合值类型):

let futuramaDict = NSArray(contentsOf: xmlFile!) as? [NSDictionary]

futuramaDict {
     "Cartoon" : "Futurama"
     "Length" : 120
     "MainCharacter" : "Philip J. Fry"
     "ClosestFriends" : ["Bender","Leela","Zoidberg"]
     }

我离开了其他键值对,所以我没有用不相关的内容填充帖子

5 个答案:

答案 0 :(得分:1)

更多" swifty"方式:

for (key, val) in xmlDict where val == nil {
    print("Found a nil value for this key: \(key)")
}

答案 1 :(得分:1)

您可以查看一行

xml.values.filter({ $0 == nil }).isEmpty

这是完整的代码段

let xml: [String: String?] = [
    "key1" : "Value1",
    "key2" : "Value2",
    "key3" : nil,
    "key4" : "Value4"
]

if xml.values.filter({ $0 == nil }).isEmpty
{
    print("Plenty of values")
}
else
{
    print("nil :(")
}

答案 2 :(得分:0)

此代码应达到您的目的:

var values = [Any]()

for index in 1 ... 30 {

    let key = "key\(index)" // Generates "key1" through "key30"

    guard let value = xmlDict[key] else {
        values.removeAll()
        break // Abort loop
    }

    values.append(values)
}

// Next: Process contents of array 'values' 
// (will be empty if any key was absent)

答案 3 :(得分:0)

快速而简短的解决方案:

if xmlDict.values.contains(where: {$0 == nil}) {
    print("Dict contains at least one nil value")
}

如果您想要查找一组预定义的键:

let keysToLookFor = ["k1", "k2", "k3", "k4"]
if keysToLookFor.contains(where: {xmlDict[$0] == nil}) {
    print("Dict contains at least one nil value")
}

用于测试的样本字典:

let xmlDict: [String: Any?] = ["k1": 22, "k2": Int(2), "k3": nil]

答案 4 :(得分:0)

这个怎么样 -

let hasAnyKeyNil = dic.keys.contains(where: { dic[$0]! == nil })