Bird
Raised Fist0
Swiftprogramming~20 mins

Dictionary methods and default values in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Dictionary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using dictionary default values?
Consider the following Swift code. What will be printed when it runs?
Swift
var scores = ["Alice": 10, "Bob": 5]

scores["Charlie", default: 0] += 3
print(scores)
A["Alice": 10, "Bob": 5, "Charlie": 3]
B["Alice": 10, "Bob": 5]
C["Alice": 10, "Bob": 5, "Charlie": 0]
DRuntime error
Attempts:
2 left
💡 Hint
Look at how the default value is used to add or update the dictionary entry.
❓ Predict Output
intermediate
2:00remaining
What does this Swift code print when using the removeValue method?
Given this Swift code, what will be printed?
Swift
var fruits = ["apple": 3, "banana": 2, "orange": 5]

let removed = fruits.removeValue(forKey: "banana")
print(removed ?? "none")
print(fruits)
A
nil
["apple": 3, "banana": 2, "orange": 5]
B
none
["apple": 3, "orange": 5]
C
2
["apple": 3, "banana": 2, "orange": 5]
D
2
["apple": 3, "orange": 5]
Attempts:
2 left
💡 Hint
removeValue returns the removed value or nil if key not found.
🔧 Debug
advanced
2:00remaining
Why does this Swift code cause a runtime error?
Examine this Swift code snippet. Why does it crash at runtime?
Swift
var dict = ["x": 1, "y": 2]

let value = dict["z"]!
print(value)
ABecause the dictionary is immutable and cannot be accessed.
BBecause key "z" does not exist, force unwrap causes a crash.
CBecause the dictionary keys must be integers, not strings.
DBecause the print statement is missing parentheses.
Attempts:
2 left
💡 Hint
Check what happens when you force unwrap a nil optional.
🧠 Conceptual
advanced
2:00remaining
How does the default value subscript work in Swift dictionaries?
Which statement best describes how the default value subscript works in Swift dictionaries?
AIt always inserts the default value for the key, even if the key exists.
BIt returns nil if the key is missing and does not modify the dictionary.
CIt returns the value for the key if present; otherwise, it inserts the default value and returns it.
DIt throws an error if the key is not found.
Attempts:
2 left
💡 Hint
Think about whether the dictionary changes when using the default value subscript.
❓ Predict Output
expert
3:00remaining
What is the final content of the dictionary after this Swift code runs?
Analyze the code below and determine the final dictionary content printed.
Swift
var inventory = ["pen": 3, "notebook": 5]

inventory["pen", default: 0] += 2
inventory["eraser", default: 0] += 1
inventory["notebook", default: 0] -= 3
print(inventory)
A["pen": 5, "notebook": 2, "eraser": 1]
B["pen": 3, "notebook": 5, "eraser": 1]
C["pen": 5, "notebook": -3, "eraser": 1]
D["pen": 5, "notebook": 2]
Attempts:
2 left
💡 Hint
Remember the default value subscript inserts missing keys and allows arithmetic updates.

Practice

(1/5)
1. What does the updateValue(_:forKey:) method do in a Swift dictionary?
easy
A. It updates the value for a given key and returns the old value if it existed.
B. It removes the key and its value from the dictionary.
C. It returns the value for a key or a default if the key is missing.
D. It creates a new dictionary with updated keys.

Solution

  1. Step 1: Understand updateValue method purpose

    The updateValue(_:forKey:) method changes the value for a specified key in the dictionary.
  2. Step 2: Check return behavior

    This method returns the old value if the key existed, otherwise nil.
  3. Final Answer:

    It updates the value for a given key and returns the old value if it existed. -> Option A
  4. Quick Check:

    updateValue returns old value or nil [OK]
Hint: Remember updateValue returns old value if key exists [OK]
Common Mistakes:
  • Confusing updateValue with removeValue
  • Thinking it returns the new value
  • Assuming it creates a new dictionary
2. Which of the following is the correct syntax to get a value from a dictionary with a default in Swift?
easy
A. let value = dict[key, default: 0]
B. let value = dict.get(key, default: 0)
C. let value = dict[key] ?? 0
D. let value = dict.value(forKey: key, default: 0)

Solution

  1. Step 1: Recall Swift dictionary default value syntax

    Swift dictionaries allow accessing values with a default using dict[key, default: defaultValue].
  2. Step 2: Compare options

    let value = dict[key, default: 0] matches the correct syntax. let value = dict[key] ?? 0 uses nil-coalescing but is not the dictionary default syntax.
  3. Final Answer:

    let value = dict[key, default: 0] -> Option A
  4. Quick Check:

    Use dict[key, default:] for default values [OK]
Hint: Use square brackets with default: for safe dictionary access [OK]
Common Mistakes:
  • Using get() method which doesn't exist
  • Confusing nil-coalescing with dictionary default syntax
  • Using value(forKey:) which is for NSObject
3. What is the output of this Swift code?
var scores = ["Alice": 10, "Bob": 8]
let oldValue = scores.updateValue(12, forKey: "Alice")
let missingValue = scores.updateValue(5, forKey: "Charlie")
print(oldValue, missingValue, scores)
medium
A. nil Optional(5) ["Alice": 12, "Bob": 8, "Charlie": 5]
B. 10 5 ["Alice": 12, "Bob": 8, "Charlie": 5]
C. Optional(10) nil ["Alice": 12, "Bob": 8, "Charlie": 5]
D. Optional(12) Optional(5) ["Alice": 10, "Bob": 8, "Charlie": 5]

Solution

  1. Step 1: Understand updateValue return values

    Updating "Alice" from 10 to 12 returns old value Optional(10). Adding "Charlie" returns nil because key was missing.
  2. Step 2: Check dictionary after updates

    Dictionary now has "Alice":12, "Bob":8, and "Charlie":5.
  3. Final Answer:

    Optional(10) nil ["Alice": 12, "Bob": 8, "Charlie": 5] -> Option C
  4. Quick Check:

    updateValue returns old value or nil [OK]
Hint: updateValue returns old value wrapped in Optional or nil if new key [OK]
Common Mistakes:
  • Expecting updateValue to return new value
  • Forgetting Optional wrapping
  • Not updating dictionary correctly
4. Identify the error in this Swift code snippet:
var dict = ["a": 1, "b": 2]
let removed = dict.removeValue(forKey: "c")
print(removed!)
medium
A. Dictionary keys must be integers, not strings.
B. Force unwrapping removed causes runtime crash if key missing.
C. removeValue(forKey:) does not exist for dictionaries.
D. print statement syntax is incorrect.

Solution

  1. Step 1: Understand removeValue return type

    removeValue(forKey:) returns an Optional value. If key is missing, it returns nil.
  2. Step 2: Analyze force unwrapping

    Force unwrapping removed! when key "c" is missing causes a runtime crash.
  3. Final Answer:

    Force unwrapping removed causes runtime crash if key missing. -> Option B
  4. Quick Check:

    Force unwrap nil causes crash [OK]
Hint: Avoid force unwrapping optional from removeValue without check [OK]
Common Mistakes:
  • Assuming removeValue always returns a value
  • Ignoring optional unwrapping
  • Thinking removeValue removes all keys
5. You have a dictionary var inventory = ["apple": 3, "banana": 5]. Write code to safely add 2 to the count of "orange", even if it doesn't exist yet, using dictionary default values. What is the correct way?
hard
A. inventory["orange"] = inventory["orange"]! + 2
B. inventory["orange"] = inventory["orange"] ?? 0 + 2
C. inventory.updateValue(inventory["orange"]! + 2, forKey: "orange")
D. inventory["orange"] = inventory["orange", default: 0] + 2

Solution

  1. Step 1: Understand safe addition with default

    Using inventory["orange", default: 0] returns 0 if "orange" key is missing.
  2. Step 2: Increment value safely

    Adding 2 to this default value and assigning back to inventory["orange"] updates or creates the key safely.
  3. Final Answer:

    inventory["orange"] = inventory["orange", default: 0] + 2 -> Option D
  4. Quick Check:

    dict[key] = dict[key, default: 0] + value for safe increments [OK]
Hint: Use dict[key] = dict[key, default: 0] + amount to add safely [OK]
Common Mistakes:
  • Force unwrapping missing keys causing crash
  • Using += on read-only default subscript
  • Using updateValue without checking for nil
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