Swift .removeValue()
Anonymous contributor
Published May 8, 2023
Contribute to Docs
The .removeValue() method will remove a key-value pairing from a dictionary based on a given key. If the key exists in the dictionary, the method will return the removed value. However, if the key is not found, the method will return nil.
Syntax
dictionaryInstance.removeValue(forKey: key)
The dictionaryInstance is the dictionary in which the key-value pairing will be removed. The key parameter is the key to remove.
Example
In the example below, the fruitBasket dictionary is checked to see if the key Apples exists. If it does, it will remove that key and print the corresponding value. If it doesn’t, a value of nil is returned.
var fruitBasket = ["Apples":3,"Bananas":7,"Oranges":2,"Pineapples":4,]if let removedValue = fruitBasket.removeValue(forKey: "Apples") {print(removedValue) // Output: 3} else {print("The key 'Apples' does not exist in the dictionary.")}
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours