Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically remove null value from swift dictionary using function

Tags:

ios

swift

I have following code for dictionary

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

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

like image 317
Gunja Patel Avatar asked Jul 27 '15 07:07

Gunja Patel


2 Answers

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

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()
like image 140
Antonio Avatar answered Nov 19 '22 14:11

Antonio


Swift 5 adds compactMapValues(_:), which would let you do

let filteredDict = dict.compactMapValues { $0 is NSNull ? nil : $0 }
like image 5
Rudedog Avatar answered Nov 19 '22 12:11

Rudedog