Use Dictionary Methods in Swift
Written by Team Kodeco
In Swift, dictionaries are collection of key-value pairs. Dictionaries are useful when you need to store values that are associated with a unique identifier.
count
The count
property returns the number of key-value pairs in a dictionary:
var myDict = ["a": 1, "b": 2, "c": 3]
print(myDict.count) // 3
isEmpty
The isEmpty
property returns a Boolean value indicating whether the dictionary is empty or not:
var myDict: [String: Int] = [:]
print(myDict.isEmpty) // true
myDict["a"] = 1
print(myDict.isEmpty) // false
updateValue(_:forKey:)
The updateValue(_:forKey:)
method updates the value associated with a given key and returns the old value or nil if there was no value associated with the key:
var myDict = ["a": 1, "b": 2, "c": 3]
let oldValue = myDict.updateValue(4, forKey: "c")
print(myDict) // ["a": 1, "b": 2, "c": 4]
if let oldValue = oldValue {
print(oldValue) // 3
}
removeValue(forKey:)
The removeValue(forKey:)
method removes the key-value pair for a given key and returns the removed value or nil if there was no value associated with the key:
var myDict = ["a": 1, "b": 2, "c": 3]
let removedValue = myDict.removeValue(forKey: "b")
print(myDict) // ["a": 1, "c": 3]
if let removedValue = removedValue {
print(removedValue) // 2
}
Iterating over a dictionary
You can use a for-in loop to iterate over the key-value pairs in a dictionary:
var myDict = ["a": 1, "b": 2, "c": 3]
for (key, value) in myDict {
print("key: \(key), value: \(value)")
}
// Output:
// key: a, value: 1
// key: b, value: 2
// key: c, value: 3
keys and values properties
You can also use the keys
and values
properties to access the keys and values of a dictionary separately:
let myDict = ["a": 1, "b": 2, "c": 3]
let keys = Array(myDict.keys)
let values = Array(myDict.values)
print(keys) // ["a", "b", "c"]
print(values) // [1, 2, 3]
filter(_:)
The filter(_:)
method returns a new dictionary containing only the key-value pairs that satisfy the given predicate:
let myDict = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5]
let filteredDict = myDict.filter { $0.value > 2 }
print(filteredDict) // ["c": 3, "d": 4, "e": 5]
mapValues(_:)
The mapValues(_:)
method returns a new dictionary by mapping the values of the original dictionary using the given closure:
let myDict = ["a": 1, "b": 2, "c": 3]
let mappedDict = myDict.mapValues { $0 * 2 }
print(mappedDict) // ["a": 2, "b": 4, "c": 6]