Swift:如何从Dictionary中删除空值? [英] Swift: How to remove a null value from Dictionary?
问题描述
我是Swift的新手,我在从JSON文件中过滤NULL值并将其设置为Dictionary时遇到问题。
我从服务器获得空值的JSON响应,它崩溃了我的应用程序。
I'm new in Swift and I have a problem with filtering NULL values from JSON file and setting it into Dictionary. I getting JSON response from the server with null values and it crashes my app.
以下是JSON回复:
"FirstName": "Anvar",
"LastName": "Azizov",
"Website": null,
"About": null,
我将非常感谢您提供帮助以解决问题。
I will be very appreciated for help to deal with it.
UPD1: At这一刻我决定以下一种方式做到这一点:
UPD1: At this moment I decided to do it in a next way:
if let jsonResult = responseObject as? [String: AnyObject] {
var jsonCleanDictionary = [String: AnyObject]()
for (key, value) in enumerate(jsonResult) {
if !(value.1 is NSNull) {
jsonCleanDictionary[value.0] = value.1
}
}
}
推荐答案
您可以创建一个包含相应值为零的键的数组:
You can create an array containing the keys whose corresponding values are nil:
let keysToRemove = dict.keys.array.filter { dict[$0]! == nil }
然后循环遍历该数组的所有元素并从字典中删除键:
and next loop through all elements of that array and remove the keys from the dictionary:
for key in keysToRemove {
dict.removeValueForKey(key)
}
更新2017.01.17
力量展开算子有点难看,虽然安全,但正如评论中所解释的那样。可能有其他几种方法可以实现相同的结果,相同方法的更好看方式是:
The force unwrapping operator is a bit ugly, although safe, as explained in the comments. There are probably several other ways to achieve the same result, a better-looking way of the same method is:
let keysToRemove = dict.keys.filter {
guard let value = dict[$0] else { return false }
return value == nil
}
这篇关于Swift:如何从Dictionary中删除空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!