Bird
0
0

You want to safely iterate over a dictionary scores to print keys and values. Which Swift loop ensures safety and prevents runtime errors?

hard📝 Application Q15 of 15
Swift - Loops
You want to safely iterate over a dictionary scores to print keys and values. Which Swift loop ensures safety and prevents runtime errors?
Afor i in 0...scores.count { print(scores[i]) }
Bfor key in scores.keys { print(scores[key]) }
Cfor (key, value) in scores { print(key, value) }
Dwhile true { print(scores) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary iteration in Swift

    Swift allows safe iteration over dictionaries using for (key, value) in dictionary.
  2. Step 2: Evaluate options for safety

    for (key, value) in scores { print(key, value) } uses correct syntax and safely accesses keys and values. for i in 0...scores.count { print(scores[i]) } is invalid for dictionaries, C risks optional unwrapping, D causes infinite loop.
  3. Final Answer:

    for (key, value) in scores { print(key, value) } -> Option C
  4. Quick Check:

    Safe dictionary loop = for (key, value) in scores { print(key, value) } [OK]
Quick Trick: Use for (key, value) in dictionary for safe iteration [OK]
Common Mistakes:
  • Using index-based loops on dictionaries
  • Forgetting optional unwrapping for dictionary values
  • Creating infinite loops unintentionally

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes