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

6

115

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
Hautbois answered 29/9, 2015 at 14:41 Comment(0)
M
215

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)
Mush answered 29/9, 2015 at 14:52 Comment(5)
this should now be called dict.removeValue(willRemoveKey) since it looks like .removeValueForKey has been renamed - thanks for the help!Sendoff
So nice and so clean. Love it!Hyacinthhyacintha
If your values are optionals how can the subscript syntax work?Hm
Has anyone else noticed that the docs say this is O(n) where n is the size of the dictionary?!Futrell
@Hm Assigning the subscript to nil always deletes the key. To assign a true nil value in a dictionary with an optional Value type, assign .some(nil).Aluminate
W
38

Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers

Whirlybird answered 2/9, 2016 at 8:45 Comment(0)
L
13
dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil
Littlejohn answered 29/9, 2015 at 14:51 Comment(0)
W
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"]
Words answered 10/10, 2022 at 7:12 Comment(0)
S
0

For serial removal:

let forbidenParameters = [
            "key1",
            "key2",
            "key3"
        ]       
let cleanParameters = parameters.filter { !forbidenParameters.contains($0.key) }
Sulfapyrazine answered 18/1 at 11:9 Comment(0)
D
-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
Detruncate answered 22/6, 2023 at 4:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.