Bird
Raised Fist0
Swiftprogramming~10 mins

Dictionary creation and access in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Dictionary creation and access
Start
↓
Create Dictionary
↓
Add Key-Value Pairs
↓
Access Value by Key
↓
Check if Key Exists?
No→Return nil or default
Yes↓
Use Value
↓
End
This flow shows how to create a dictionary, add key-value pairs, then access values safely by checking if the key exists.
Execution Sample
Swift
var fruits = ["apple": "red", "banana": "yellow"]
let appleColor = fruits["apple"]
let orangeColor = fruits["orange"]
Create a dictionary of fruits and colors, then access colors by keys.
Execution Table
StepActionDictionary StateAccess KeyValue Retrieved
1Create dictionary with apple and banana{"apple": "red", "banana": "yellow"}--
2Access value for key "apple"{"apple": "red", "banana": "yellow"}apple"red"
3Access value for key "orange" (not present){"apple": "red", "banana": "yellow"}orangenil
💡 Finished accessing keys; orange key not found returns nil
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
fruitsempty{"apple": "red", "banana": "yellow"}{"apple": "red", "banana": "yellow"}{"apple": "red", "banana": "yellow"}
appleColornilnilOptional("red")Optional("red")
orangeColornilnilnilnil
Key Moments - 2 Insights
Why does accessing fruits["orange"] return nil instead of an error?
Because the dictionary does not have the key "orange", Swift returns nil safely instead of crashing, as shown in execution_table row 3.
Can we add new key-value pairs after dictionary creation?
Yes, since 'fruits' is declared with 'var', it is mutable and you can add or change pairs after creation.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value is retrieved when accessing the key "apple"?
Anil
B"yellow"
C"red"
D"orange"
💡 Hint
Check execution_table row 2 under 'Value Retrieved'
At which step does the dictionary get created with initial values?
AStep 1
BStep 2
CStep 3
DNo step creates it
💡 Hint
Look at execution_table row 1 under 'Action' and 'Dictionary State'
If we add fruits["orange"] = "orange" after step 3, what will fruits["orange"] return?
Anil
B"orange"
C"red"
DError
💡 Hint
Recall that 'fruits' is mutable (var) and adding a key-value pair updates the dictionary
Concept Snapshot
Dictionary creation: var dict = ["key": "value", ...]
Access value: dict["key"] returns optional value
If key missing, returns nil safely
Use var for mutable dictionary
Use let for constant dictionary
Full Transcript
This example shows how to create a dictionary in Swift with keys and values. We start by making a dictionary named 'fruits' with two pairs: apple-red and banana-yellow. Then we access the value for the key 'apple' which returns 'red'. Next, we try to access 'orange' which is not in the dictionary, so Swift returns nil safely without error. The dictionary is mutable because it is declared with var, so we can add or change pairs later. This teaches how to create and access dictionaries safely in Swift.

Practice

(1/5)
1. What is a dictionary in Swift used for?
easy
A. To store data in key-value pairs for quick lookup
B. To store a list of values without keys
C. To perform mathematical calculations
D. To create user interface elements

Solution

  1. Step 1: Understand dictionary purpose

    Dictionaries store data as pairs of keys and values, allowing fast access by key.
  2. Step 2: Compare options

    Only To store data in key-value pairs for quick lookup correctly describes this key-value storage purpose.
  3. Final Answer:

    To store data in key-value pairs for quick lookup -> Option A
  4. Quick Check:

    Dictionaries = key-value storage [OK]
Hint: Remember: dictionaries pair keys with values for fast access [OK]
Common Mistakes:
  • Confusing dictionaries with arrays (which have no keys)
  • Thinking dictionaries perform calculations
  • Assuming dictionaries create UI elements
2. Which of the following is the correct way to create a dictionary in Swift?
easy
A. let dict = ("apple", 1), ("banana", 2)
B. let dict = ["apple": 1, "banana": 2]
C. let dict = {"apple": 1, "banana": 2}
D. let dict = ["apple", 1, "banana", 2]

Solution

  1. Step 1: Identify Swift dictionary syntax

    Swift dictionaries use square brackets with key-value pairs separated by colons.
  2. Step 2: Check each option

    let dict = ["apple": 1, "banana": 2] uses correct syntax: ["key": value, ...]. Others use tuples, braces, or arrays incorrectly.
  3. Final Answer:

    let dict = ["apple": 1, "banana": 2] -> Option B
  4. Quick Check:

    Dictionary syntax = [key: value] [OK]
Hint: Use square brackets with colons for key-value pairs [OK]
Common Mistakes:
  • Using parentheses instead of square brackets
  • Using curly braces which define closures
  • Listing keys and values without colons
3. What will be the output of this Swift code?
let fruits = ["apple": 3, "banana": 5]
print(fruits["banana"] ?? 0)
medium
A. 5
B. nil
C. banana
D. 0

Solution

  1. Step 1: Access dictionary value by key

    fruits["banana"] looks up the value for key "banana", which is 5.
  2. Step 2: Use nil-coalescing operator

    The ?? 0 means if the key is missing (nil), print 0; here key exists, so print 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    fruits["banana"] = 5 [OK]
Hint: Use ?? to provide default if key missing [OK]
Common Mistakes:
  • Expecting nil instead of default value
  • Printing the key instead of the value
  • Confusing optional with direct value
4. Identify the error in this Swift code snippet:
var scores = ["Alice": 90, "Bob": 85]
scores["Charlie"] = 95
print(scores["Charlie"])
medium
A. Cannot add new key-value pairs to a dictionary
B. Dictionary keys must be integers
C. Syntax error in dictionary declaration
D. Missing unwrap of optional when printing

Solution

  1. Step 1: Check dictionary modification

    Adding a new key-value pair to a var dictionary is allowed, so no error there.
  2. Step 2: Understand optional access

    Accessing scores["Charlie"] returns an optional Int?; printing it directly shows Optional(95), not 95.
  3. Step 3: Identify missing unwrap

    To print the value without Optional(...), unwrap it safely or use ?? to provide default.
  4. Final Answer:

    Missing unwrap of optional when printing -> Option D
  5. Quick Check:

    Dictionary access returns optional, unwrap needed [OK]
Hint: Remember dictionary access returns optional, unwrap before use [OK]
Common Mistakes:
  • Thinking keys must be integers
  • Assuming dictionary is immutable by default
  • Ignoring optional nature of dictionary values
5. Given a dictionary let items = ["pen": 3, "notebook": 0, "eraser": 2], which Swift code correctly creates a new dictionary containing only items with quantity greater than zero?
hard
A. let filtered = items.compactMap { $0.value > 0 }
B. let filtered = items.filter { $0.key > 0 }
C. let filtered = items.filter { $0.value > 0 }
D. let filtered = items.map { $0.value > 0 }

Solution

  1. Step 1: Understand filtering dictionary by value

    We want to keep pairs where value > 0, so filter with condition on $0.value.
  2. Step 2: Analyze each option

    let filtered = items.filter { $0.value > 0 } uses filter with correct condition. let filtered = items.filter { $0.key > 0 } incorrectly compares key (a String) to 0. Options A and C use map/compactMap which transform values, not filter pairs.
  3. Final Answer:

    let filtered = items.filter { $0.value > 0 } -> Option C
  4. Quick Check:

    Filter dictionary by value > 0 = let filtered = items.filter { $0.value > 0 } [OK]
Hint: Use filter with $0.value condition to keep matching pairs [OK]
Common Mistakes:
  • Filtering by key instead of value
  • Using map instead of filter for selection
  • Using compactMap which changes type, not filters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard