112

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
do it better
  • 4,627
  • 6
  • 25
  • 41

5 Answers5

209

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)
Community
  • 1
  • 1
Kametrixom
  • 14,673
  • 7
  • 45
  • 62
37

Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers

Sasho
  • 3,532
  • 1
  • 31
  • 30
12
dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil
Fantini
  • 2,067
  • 21
  • 32
4
var dict: [String: Any] = ["device": "iPhone", "os": "12.0", "model": "iPhone 12 Pro Max"]

if let index = dict.index(forKey: "device") {
   dict.remove(at: index)
}

print(dict) // ["os": "12.0", "model": "iPhone 12 Pro Max"]
Sai kumar Reddy
  • 1,751
  • 20
  • 23
-1
let dict = ["k1": "v1" , "k2": "v2"]
  for ( k, _) in dict{
        dict.removeValue(forKey: k)
       }
  • Just Loop through it and remove value for key
  • removeValue(forKey : k) for value