Swift Dictionaries
This tutorial belongs to the Swift series
We use dictionaries to create a collection of key-value pairs.
Here is how to create a dictionary with 1 key-value pairs, where the key is a String and the value is an Int:
var dict = ["Roger": 8, "Syd": 7]
In this case the type is inferred. You can also explicitly set the type at declaration time:
var dict: [String: Int] = ["Roger": 8, "Syd": 7]
In this example we create an empty dictionary of Int keys and String values:
var dict = [String: Int]()
//or
var dict: [String: Int] = [:]
You can access the value assigned to a key using this syntax:
var dict = ["Roger": 8, "Syd": 7]
dict["Roger"] //8
dict["Syd"] //7
You can change the value assigned to a key in this way:
dict["Roger"] = 9
A dictionary must be declared as
varto be modified. If itβs declared withlet, you cannot modify it by adding or removing elements.
Use the same syntax to add a new key/value pair:
dict["Tina"] = 4
To remove a key/value paid, assign the value to nil:
dict["Tina"] = nil
Or call the removeValue(forKey:) method:
dict.removeValue(forKey: "Tina")
To get the number of items in the dictionary, use the count property:
var dict = ["Roger": 8, "Syd": 7]
dict.count //2
If a dictionary is empty, its isEmpty property is true.
var dict = [String: Int]()
dict.isEmpty //true
There are a lot of methods related to dictionaries, but those are the basic ones.
Dictionaries are passed by value, which means if you pass it to a function, or return it from a function, the dictionary is copied.
Dictionaries are collections, and they can be iterated over in loops.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.