Given a Swift dictionary [String: Int], how can you use a switch with value binding to print keys with values greater than 10 and others separately?
hard📝 Application Q9 of 15
Swift - Control Flow
Given a Swift dictionary [String: Int], how can you use a switch with value binding to print keys with values greater than 10 and others separately?
Afor (key, value) in dict {
switch (key, value) {
case let (k, v) where v > 10:
print("\(k): Large")
default:
print("\(k): Small")
}
}
Bfor (key, value) in dict {
switch key {
case let k where value > 10:
print("\(k): Large")
default:
print("\(k): Small")
}
}
Cfor (key, value) in dict {
switch value {
case let x where x > 10:
print("\(key): Large")
default:
print("\(key): Small")
}
}
Dfor (key, value) in dict {
switch value {
case let x where x < 10:
print("\(key): Large")
default:
print("\(key): Small")
}
}
Step-by-Step Solution
Solution:
Step 1: Identify correct switch subject
We want to switch on the value to check if it's greater than 10.
Step 2: Check value binding and conditions
for (key, value) in dict {
switch value {
case let x where x > 10:
print("\(key): Large")
default:
print("\(key): Small")
}
} switches on value, binds it as x, and uses where clause correctly.
Final Answer:
switch value { case let x where x > 10: print("\(key): Large") default: print("\(key): Small") } -> Option C
Quick Check:
Switch on value with binding and where clause [OK]
Quick Trick:Switch on value, not key, to check numeric conditions [OK]
Common Mistakes:
Switching on key but using value in where clause
Mixing up conditions for large/small
Incorrect tuple binding in switch
Master "Control Flow" in Swift
9 interactive learning modes - each teaches the same concept differently