Bird
0
0

You have a dictionary of student names and their scores:

hard📝 Application Q15 of 15
Swift - Loops
You have a dictionary of student names and their scores:
let scores = ["Alice": 85, "Bob": 92, "Cara": 78]

Using a for-in loop, how do you print only the names of students who scored above 80?
Afor name in scores.keys { if scores[name] > 80 { print(name) } }
Bfor (name, score) in scores { if score > 80 { print(name) } }
Cfor score in scores.values { if score > 80 { print(score) } }
Dfor name in scores { if scores[name] > 80 { print(name) } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary iteration with key-value pairs

    Using 'for (name, score) in scores' lets you access both keys and values directly.
  2. Step 2: Apply condition to print names with score above 80

    Inside the loop, check if score > 80, then print the name.
  3. Final Answer:

    for (name, score) in scores { if score > 80 { print(name) } } -> Option B
  4. Quick Check:

    Use (key, value) pairs to filter dictionary [OK]
Quick Trick: Use (key, value) in dictionary to access both [OK]
Common Mistakes:
  • Trying to loop only keys or values without pairing
  • Forgetting to unwrap optional values
  • Printing scores instead of names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes