Removes the given key and its associated value from the dictionary.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
@discardableResult mutating func removeValue(forKey key: Key) -> Value?
Parameters
key
The key to remove along with its associated value.
Return Value
The value that was removed, or nil
if the key was not present in the dictionary.
Discussion
If the key is found in the dictionary, this method returns the key’s associated value. On removal, this method invalidates all indices with respect to the dictionary.
var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
if let value = hues.removeValue(forKey: "Coral") {
print("The value \(value) was removed.")
}
// Prints "The value 16 was removed."
If the key isn’t found in the dictionary, remove
returns nil
.
if let value = hues.removeValueForKey("Cerise") {
print("The value \(value) was removed.")
} else {
print("No value found for that key.")
}
// Prints "No value found for that key.""
Complexity: O(n), where n is the number of key-value pairs in the dictionary.