Swift - Removing an Item from the Dictionary

Introduction

To remove an item from a dictionary, you can simply set it to nil :

Demo

var myTable =  [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

myTable["Microsoft"] = nil;
print(myTable.count)      //2

Result

The number of items inside the dictionary would now be reduced by one.

removeValueForKey() method

Alternatively, you can use the removeValueForKey() method,

Demo

var myTable =  [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

if let removedValue = myTable.removeValueForKey("Microsoft") {
    print("Platform removed: \(removedValue)")
} else {/* ww  w .java 2s. c o  m*/
    print("Key not found")
}

removeValueForKey() method returns the value of the key to be removed, and nil if the key does not exist.

Related Topic