How to remove a key-value pair from swift dictionary?

SwiftDictionarySwift2

Swift Problem Overview


I want to remove a key-value pair from a dictionary like in the example.

var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need

Swift Solutions


Solution 1 - Swift

You can use this:

dict[willRemoveKey] = nil

or this:

dict.removeValueForKey(willRemoveKey)

The only difference is that the second one will return the removed value (or nil if it didn't exist)

Swift 3

dict.removeValue(forKey: willRemoveKey)

Solution 2 - Swift

Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers

Solution 3 - Swift

dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondo it betterView Question on Stackoverflow
Solution 1 - SwiftKametrixomView Answer on Stackoverflow
Solution 2 - SwiftSashoView Answer on Stackoverflow
Solution 3 - SwiftFantiniView Answer on Stackoverflow