0
0
Swiftprogramming~20 mins

Dictionary creation and access in Swift - Practice Problems & Coding Challenges

Choose your learning style9 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 dictionary access?
Consider the following Swift code. What will be printed?
Swift
let fruits = ["apple": 3, "banana": 5, "orange": 2]
print(fruits["banana"] ?? 0)
A0
BOptional(5)
Cbanana
D5
Attempts:
2 left
💡 Hint
Remember that using ?? provides a default value if the key is missing.
Predict Output
intermediate
2:00remaining
What does this dictionary creation code produce?
What is the content of the dictionary 'numbers' after this code runs?
Swift
let numbers = Dictionary(uniqueKeysWithValues: [(1, "one"), (2, "two"), (3, "three")])
print(numbers)
AError: Cannot create dictionary this way
B[1: "one", 2: "two", 3: "three"]
C[(1, "one"), (2, "two"), (3, "three")]
D["one": 1, "two": 2, "three": 3]
Attempts:
2 left
💡 Hint
Dictionary(uniqueKeysWithValues:) creates a dictionary from a sequence of key-value pairs.
Predict Output
advanced
2:00remaining
What error does this Swift dictionary code raise?
What error will occur when running this code?
Swift
var dict = ["a": 1, "b": 2]
let value = dict["c"]!
print(value)
ARuntime error: Unexpectedly found nil while unwrapping an Optional value
BCompile-time error: Key not found in dictionary
CPrints 0
DPrints nil
Attempts:
2 left
💡 Hint
Using ! to unwrap an Optional that is nil causes a runtime crash.
🧠 Conceptual
advanced
2:00remaining
How many items are in the dictionary after this code?
After running this Swift code, how many key-value pairs does the dictionary 'items' contain?
Swift
var items = ["x": 10, "y": 20]
items["z"] = 30
items["x"] = nil
A1
B3
C2
D0
Attempts:
2 left
💡 Hint
Setting a dictionary value to nil removes the key.
🔧 Debug
expert
2:00remaining
What is the output of this Swift dictionary comprehension?
What will be printed by this Swift code?
Swift
let squares = Dictionary(uniqueKeysWithValues: (1...3).map { ($0, $0 * $0) })
print(squares[2] ?? -1)
A4
B2
C-1
DOptional(4)
Attempts:
2 left
💡 Hint
The dictionary maps numbers to their squares. Accessing key 2 returns 4.