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

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


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)


Swift 5, Swift 4, and Swift 3:

x.removeValue(forKey: "MyUndesiredKey")

Cheers


dict.removeValue(forKey: willRemoveKey)

Or you can use the subscript syntax:

dict[willRemoveKey] = nil