Bird
0
0

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:
  1. Step 1: Identify correct switch subject

    We want to switch on the value to check if it's greater than 10.
  2. 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.
  3. Final Answer:

    switch value { case let x where x > 10: print("\(key): Large") default: print("\(key): Small") } -> Option C
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes