Swift – Add Element to Dictionary
Welcome to Swift Tutorial. In this tutorial, we will learn how to append elements to a Swift Dictionary.
To append an element to a dictionary in Swift programming, assign a value to the Dictionary with a key that is not already present.
myDictionary[new_key] = value
Note that the new_key
has to be unique with respect to the keys already present in the dictionary. value
does not have any constraints.
If the new_key
is not unique, the value for the existing key shall be updated.
Also, remember that the datatypes of new_key and value should obey the datatypes of the dictionary’s key and value datatypes.
Example 1 – Append an Element to Swift Dictionary
In this example, we shall create a dictionary with some initial values, and append a new (key, value) pair to the dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
myDictionary["Surya"] = 88
for (key, value) in myDictionary {
print("\(key) : \(value)")
}
Output
Raghu : 82
Mohan : 75
John : 79
Surya : 88
Conclusion
In this Swift Tutorial, we have learned how to append an element to a Swift Dictionary with the help of example programs.