使用函数从swift字典dynamic删除空值

我有以下的字典代码

var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()] 

我已经使用下面的代码删除了具有空值的键

 var keys = dic.keys.array.filter({dic[$0] is NSNull}) for key in keys { dic.removeValueForKey(key) } 

它适用于静态字典,但我想要做dynamic的,我想要做它使用函数,但每当我把字典作为参数它作为一个让手段常量,所以不能删除空密钥我做下面的代码

 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 } 

请告诉我这个解决scheme

而不是使用全局函数(或方法),为什么不使用一个扩展?

 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 } } 

它适用于任何genericstypes(所以不限于String, AnyObject ),您可以直接从字典本身调用它:

 var dic : [String: AnyObject] = ["FirstName": "Anvar", "LastName": "Azizov", "Website": NSNull(),"About": NSNull()] let dicWithoutNulls = dic.nullKeyRemoval() 

对于Swift 3.0 / 3.1这可能会有所帮助。 也删除NSNull对象recursion:

 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:从字典中删除null

  func removeNSNull(from dict: [AnyHashable: Any]) -> [AnyHashable: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"]) 

输出:[“name”:“Foo”,“address”:“”,“id”:“12”]

而不是使用全局函数(或方法),为什么不使用一个扩展?

  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 } }