Dynamically remove null value from swift dictionary using function

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

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

Dynamically remove null value from swift dictionary using function, Dynamically remove null value from swift dictionary using function - ios. Swift 3: Remove null from dictionary func removeNSNull(from dict: [String: Any])� Given a Python dictionary, remove any term whose value is None. The function should accommodate nested dictionaries, which occur when the value of a term is another dictionary.

For Swift 3.0 / 3.1 this could be helpful. Also removes NSNull objects recursive:

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: How to remove a null value from Dictionary?, Dynamically remove null value from swift dictionary using function. Question. I have following code for dictionary var dic : [String: AnyObject] = ["FirstName":� Create a new dictionary by using a dictionary literal. A dictionary literal is a comma-separated list of key-value pairs, in which a colon separates each key from its associated value, surrounded by square brackets. You can assign a dictionary literal to a variable or constant or pass it to a function that expects a dictionary.

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

let filteredDict = dict.compactMapValues { $0 is NSNull ? nil : $0 }

使用函数从swift字典中动态删除空值- Dynamically remove null value , I getting JSON response from the server with null values and it crashes my app. Dynamically remove null value from swift dictionary using function , Rather� You can use removeValueForKey () method to remove a key-value pair from a dictionary. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed. Here is a simple example −

Swift 3+: Remove null from dictionary

 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
}

Use:

let outputDict = removeNSNull(from: ["name": "Foo", "address": NSNull(), "id": "12"])

Output: ["name": "Foo", "address": "", "id": "12"]

Dictionary, I have following code for dictionary我有下面的字典代码var dic : [String: [英] Dynamically remove null value from swift dictionary using function. Edit: So almost 5 years later, this answer is getting downvotes because it’s not creating an “normal” JS object literal (aka map, aka hash, aka dictionary). It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties.

Swift 4

A little more efficient than the other solutions. Uses only O(n) complexity.

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

Usage: ["ok": nil, "now": "k", "foo": nil].trimmingNullValues // = ["now": "k"]

If your dictionary is mutable you could do this in place and prevent the inefficient copying:

extension Dictionary where Key == String, Value == Any? {
    mutating func trimNullValues() {
        forEach { (key, value) in
            if value == nil {
                removeValue(forKey: key)
            }
        }            
    }
}

Usage: var dict: [String: Any?] = ["ok": nil, "now": "k", "foo": nil] dict.trimNullValues() // dict now: = ["now": "k"]

Array, To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ) . protocol can be used as a dictionary's Key type, including all of Swift's basic types. or remove keys and values from a dictionary using the key-based subscript. Bridging from NSDictionary to Dictionary first calls the copy(with:) method� USE ISNULL function to handle null value declare @sql nvarchar ( 2000 ) declare @storecode int =null SET @sql = ' SELECT * FROM mch WHERE storecode = ' +convert( varchar ,ISNULL( @storecode , 1 ))+ ' ' print @sql EXECUTE sp_executesql @sql

Jinja Data Structures, Swift makes it easy to create arrays in your code using an array literal: simply You can create an empty array by specifying the Element type of your array in the Use the first and last properties for safe access to the value of the array's first and To add single elements to the end of an array, use the append(_:) method. Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function’s parameters. A function’s arguments must always be provided in the same order as the function’s parameter

Collection Types — The Swift Programming Language (Swift 5.3), Initialising an empty list is possible too, just put the square brackets with Because lists are dynamic data structures, you can add and remove elements from lists in You can add an element to a list using the append method. To retrieve the value from your dictionary, you simply use the key that you stored the value with. Specifically, a dynamic value can be: Null. A value of any of the primitive scalar data types: bool, datetime, guid, int, long, real, string, and timespan. An array of dynamic values, holding zero or more values with zero-based indexing. A property bag that maps unique string values to dynamic values.

Declarations — The Swift Programming Language (Swift 5.3), Swift's array, set, and dictionary types are implemented as generic collections. You can create an empty array of a certain type using initializer syntax: This call to the insert(_:at:) method inserts a new item with a value of "Maple Syrup" at the Similarly, you remove an item from the array with the remove(at:) method. Here the ’emp2′ record is updated while ’emp3′ is added to the dictionary. Remove Nested Dictionary Items. There are several ways to remove items from a nested dictionary. Remove an Item by Key. If you know the key of the item you want, you can use pop() method. It removes the key and returns its value.

Comments
  • func nullKeyRemoval(var dic : [String: AnyObject]) -> [String: AnyObject]{
  • Why you don't change your condition in filter function so you will get just the array with the data you want and you don't need to enumerate it again: ({!(dic[$0] is NSNull)})
  • Work, but just for embedded dictionaries that not contains embedded arrays
  • Why would you use NSDictionary and NSMutableDictionary in Swift when they have native counterparts? Function names should also start with lowercase letters. Moreover, there are a lot of forced unwrapping that could crash the code and this answer only works with String keys.