使用函数从swift字典中动态删除空值 [英] Dynamically remove null value from swift dictionary using function
问题描述
我有下面的字典代码
var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
我已经使用下面的代码删除了具有空值的键
I already remove key which have null value using below code
var keys = dic.keys.array.filter({dic[$0] is NSNull})
for key in keys {
dic.removeValueForKey(key)
}
它适用于静态字典,但我想动态地做,我想用函数完成它但是每当我把字典作为参数传递时它就像一个let意味着常量所以不能删除空键
我在下面创建代码
It works for static dictionary,But I want do it dynamically,I want to done it using function but whenever I pass dictionary as a argument it works as a let means constant so can not remove null key I make below code for that
func nullKeyRemoval(dic : [String: AnyObject]) -> [String: AnyObject]{
var keysToRemove = dic.keys.array.filter({dic[$0] is NSNull})
for key in keysToRemove {
dic.removeValueForKey(key)
}
return dic
}
请告诉我这方面的解决方案
please tell me solution for this
推荐答案
为什么不使用全局函数(或方法),为什么不将它作为的方法字典
,使用扩展名吗?
Rather than using a global function (or a method), why not making it a method of Dictionary
, using an extension?
extension Dictionary {
func nullKeyRemoval() -> Dictionary {
var dict = self
let keysToRemove = Array(dict.keys).filter { dict[$0] is NSNull }
for key in keysToRemove {
dict.removeValue(forKey: key)
}
return dict
}
}
它适用于任何泛型类型(因此不限于 String,AnyObject
),您可以直接从字典中调用它本身:
It works with any generic types (so not limited to String, AnyObject
), and you can invoke it directly from the dictionary itself:
var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
let dicWithoutNulls = dic.nullKeyRemoval()
这篇关于使用函数从swift字典中动态删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!