Ios 使用函数从swift字典中动态删除空值
我有下面的字典代码Ios 使用函数从swift字典中动态删除空值,ios,swift,Ios,Swift,我有下面的字典代码 var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()] func removeNSNull(from dict: [String: Any]) -> [String: Any] { var mutableDict = dict let keysWithEmptString =
var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
func removeNSNull(from dict: [String: Any]) -> [String: Any] {
var mutableDict = dict
let keysWithEmptString = dict.filter { $0.1 is NSNull }.map { $0.0 }
for key in keysWithEmptString {
mutableDict[key] = ""
}
return mutableDict
}
我已经使用下面的代码删除了具有空值的键
var keys = dic.keys.array.filter({dic[$0] is NSNull})
for key in keys {
dic.removeValueForKey(key)
}
它适用于静态字典,但我希望动态执行,我希望使用函数执行,但每当我将字典作为参数传递时,它将作为let-means常量执行,因此无法删除null键
我做了下面的代码
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
}
请告诉我这个的解决方案,而不是使用一个全局函数(或一个方法),为什么不使用一个扩展名将它变成一个
字典
的方法呢
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
}
}
extension NSDictionary
{
func RemoveNullValueFromDic()-> NSDictionary
{
let mutableDictionary:NSMutableDictionary = NSMutableDictionary(dictionary: self)
for key in mutableDictionary.allKeys
{
if("\(mutableDictionary.objectForKey("\(key)")!)" == "<null>")
{
mutableDictionary.setValue("", forKey: key as! String)
}
else if(mutableDictionary.objectForKey("\(key)")!.isKindOfClass(NSNull))
{
mutableDictionary.setValue("", forKey: key as! String)
}
else if(mutableDictionary.objectForKey("\(key)")!.isKindOfClass(NSDictionary))
{
mutableDictionary.setValue(mutableDictionary.objectForKey("\(key)")!.RemoveNullValueFromDic(), forKey: key as! String)
}
}
return mutableDictionary
}
}
它适用于任何泛型类型(因此不限于String,AnyObject
),您可以直接从字典本身调用它:
var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
let dicWithoutNulls = dic.nullKeyRemoval()
与其使用全局函数(或方法),为什么不使用扩展将其作为字典的方法呢
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
}
}
extension NSDictionary
{
func RemoveNullValueFromDic()-> NSDictionary
{
let mutableDictionary:NSMutableDictionary = NSMutableDictionary(dictionary: self)
for key in mutableDictionary.allKeys
{
if("\(mutableDictionary.objectForKey("\(key)")!)" == "<null>")
{
mutableDictionary.setValue("", forKey: key as! String)
}
else if(mutableDictionary.objectForKey("\(key)")!.isKindOfClass(NSNull))
{
mutableDictionary.setValue("", forKey: key as! String)
}
else if(mutableDictionary.objectForKey("\(key)")!.isKindOfClass(NSDictionary))
{
mutableDictionary.setValue(mutableDictionary.objectForKey("\(key)")!.RemoveNullValueFromDic(), forKey: key as! String)
}
}
return mutableDictionary
}
}
扩展字典
{
func RemoveNullValueFromDic()->NSDictionary
{
让mutableDictionary:NSMutableDictionary=NSMutableDictionary(dictionary:self)
用于mutableDictionary.allKeys中的键
{
如果(“\(mutableDictionary.objectForKey(“\(key)”)!”==“”)
{
mutableDictionary.setValue(“,forKey:key as!String)
}
else if(mutableDictionary.objectForKey(“\(key)”)!.iskindof类(NSNull))
{
mutableDictionary.setValue(“,forKey:key as!String)
}
else if(mutableDictionary.objectForKey(“\(key)”)!.iskindof类(NSDictionary))
{
mutableDictionary.setValue(mutableDictionary.objectForKey(“\(key)”)!.RemoveNullValueFromDic(),forKey:key as!String)
}
}
返回可变字典
}
}
对于
Swift 3.0/3.1
,这可能会有所帮助。还删除递归对象NSNull
:
extension Dictionary {
func nullKeyRemoval() -> [AnyHashable: Any] {
var dict: [AnyHashable: Any] = self
let keysToRemove = dict.keys.filter { dict[$0] is NSNull }
let keysToCheck = dict.keys.filter({ dict[$0] is Dictionary })
for key in keysToRemove {
dict.removeValue(forKey: key)
}
for key in keysToCheck {
if let valueDict = dict[key] as? [AnyHashable: Any] {
dict.updateValue(valueDict.nullKeyRemoval(), forKey: key)
}
}
return dict
}
}
Swift 3+:从字典中删除空值
var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()]
func removeNSNull(from dict: [String: Any]) -> [String: Any] {
var mutableDict = dict
let keysWithEmptString = dict.filter { $0.1 is NSNull }.map { $0.0 }
for key in keysWithEmptString {
mutableDict[key] = ""
}
return mutableDict
}
使用:
let outputDict = removeNSNull(from: ["name": "Foo", "address": NSNull(), "id": "12"])
输出:[“名称”:“Foo”,“地址”:“id”:“12”]Swift 4 比其他解决方案更有效一点。仅使用
O(n)
复杂性
extension Dictionary where Key == String, Value == Any? {
var trimmingNullValues: [String: Any] {
var copy = self
forEach { (key, value) in
if value == nil {
copy.removeValue(forKey: key)
}
}
return copy as [Key: ImplicitlyUnwrappedOptional<Value>]
}
}
用法:
变量dict:[字符串:任何?]=[“确定”:无,“现在”:“k”,“foo”:无]
dict.trimNullValues()//dict now:=[“now”:“k”]
使用reduce的Swift 4示例
let dictionary = [
"Value": "Value",
"Nil": nil
]
dictionary.reduce([String: String]()) { (dict, item) in
guard let value = item.value else {
return dict
}
var dict = dict
dict[item.key] = value
return dict
}
最干净的方法,只需一行
extension Dictionary {
func filterNil() -> Dictionary {
return self.filter { !($0.value is NSNull) }
}
}
Swift 5添加了
compactMapValues(:)
,这样您就可以
let filteredDict = dict.compactMapValues { $0 is NSNull ? nil : $0 }
支持嵌套的NSNull
要删除任何嵌套级别(包括数组和字典)中的任何NSNull
外观,请尝试以下操作:
extension Dictionary where Key == String {
func removeNullsFromDictionary() -> Self {
var destination = Self()
for key in self.keys {
guard !(self[key] is NSNull) else { destination[key] = nil; continue }
guard !(self[key] is Self) else { destination[key] = (self[key] as! Self).removeNullsFromDictionary() as? Value; continue }
guard self[key] is [Value] else { destination[key] = self[key]; continue }
let orgArray = self[key] as! [Value]
var destArray: [Value] = []
for item in orgArray {
guard let this = item as? Self else { destArray.append(item); continue }
destArray.append(this.removeNullsFromDictionary() as! Value)
}
destination[key] = destArray as? Value
}
return destination
}
}
func nullkeyremovation(var dic:[String:AnyObject])->[String:AnyObject]{为什么不在filter函数中更改条件,这样就可以得到包含所需数据的数组,而无需再次枚举:({!(dic[$0]为NSNull)})为什么在
Swift
中使用NSDictionary
和NSMutableDictionary
呢?函数名也应该以小写字母开头。此外,有很多强制展开操作可能会使代码崩溃,这个答案只适用于String
键。可以,但只适用于embe不包含嵌入式阵列的dded字典这是一个有效的解决方案。