Swift Program to Remove Null from a Dictionary

Sometimes a dictionary contains null values so to remove those null values Swift provides an in-built function named the filter() method. In the filter() method, we pass a closure which returns a boolean value indicating whether the key-value pair should be included in the resultant dictionary or not. Or we can say that if the second element(value) of a key-value pair is not nil, then it will be included in the resultant dictionary. Otherwise not.


dict.filter{$0.1 != nil}

Here, dict is the dictionary. The filter() function return key-value pairs which satisfy the given closure. The closure returns true if the second element (value) of a key-value pair is not nil. Otherwise, return false.


  • Step 1 − Create an array with key-value pairs. Here the type of the values is the optional type to store nil.

  • Step 2 − Print the original dictionary.

  • Step 3 − Now remove null from the dictionary using the filter() method.

  • Step 4 − Print the modified array.


In the following Swift program, we are going to remove null from a dictionary. So for that, we will create a dictionary with nil values (or optional values). Then we will use the filter() function to remove nil values along with their associated keys and display the result.

import Foundation
import Glibc

var myCityRank:[String:Int?] = ["Delhi": nil, "Goa": 3, "Pune": nil, "Jaipur": 2, "Kolkata": nil]

print("Original values: ", myCityRank)

// Removing nil 
myCityRank = myCityRank.filter{$0.1 != nil}
print("Dictionary without null values: \(myCityRank)")


Original values:  ["Goa": Optional(3), "Jaipur": Optional(2), "Delhi": nil, "Kolkata": nil, "Pune": nil]
Dictionary without null values: ["Jaipur": Optional(2), "Goa": Optional(3)]


So this is how we can remove null from a dictionary. To store null values in the dictionary we declare the value type is an optional type with the help of the question mark(Int?). Without an optional type, you are not able to store null values in the dictionary.

Updated on: 09-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started