swiftdictionaryswift2

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


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

Solution

  • 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)