0
0
Swiftprogramming~5 mins

Dictionary creation and access in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a dictionary in Swift?
A dictionary in Swift is a collection that stores key-value pairs. Each key is unique and is used to access its corresponding value.
Click to reveal answer
beginner
How do you create an empty dictionary in Swift?
You create an empty dictionary by specifying the key and value types inside square brackets, like this: <br>var dict = [String: Int]()
Click to reveal answer
beginner
How do you add or update a value in a Swift dictionary?
You assign a value to a key using subscript syntax: <br>dict["key"] = value. If the key exists, the value updates; if not, it adds a new pair.
Click to reveal answer
intermediate
How do you safely access a value from a Swift dictionary?
Use optional binding to check if the value exists: <br><code>if let value = dict["key"] { /* use value */ }</code>. This avoids errors if the key is missing.
Click to reveal answer
beginner
What happens if you access a key that does not exist in a Swift dictionary?
Accessing a non-existent key returns nil because dictionary values are optional when accessed by key.
Click to reveal answer
How do you declare a dictionary with String keys and Int values in Swift?
Avar dict = {String: Int}
Bvar dict = (String, Int)[]
Cvar dict = [String: Int]()
Dvar dict = [Int: String]()
What does this code do? <br> dict["age"] = 30
ACreates a new dictionary
BDeletes the key "age"
CAccesses the value for key "age"
DAdds or updates the value 30 for the key "age"
What type is returned when you access a dictionary value by key in Swift?
AAn optional of the value type
BThe value type directly
CA Boolean
DA String
How can you safely use a value from a dictionary if the key might not exist?
AUse optional binding with if let
BForce unwrap the value
CIgnore the value
DUse a for loop
Which of these is a correct way to create a dictionary with initial values?
Avar dict = ("name" => "Alice", "age" => 25)
Bvar dict = ["name": "Alice", "age": 25]
Cvar dict = {"name": "Alice", "age": 25}
Dvar dict = ["name" -> "Alice", "age" -> 25]
Explain how to create a dictionary in Swift and add a new key-value pair.
Think about how you declare types and assign values.
You got /3 concepts.
    Describe how to safely access a value from a Swift dictionary and handle the case when the key does not exist.
    Remember that dictionary lookups return optionals.
    You got /3 concepts.