Bird
0
0

You have a list of user records as dictionaries:

hard📝 Application Q15 of 15
Swift - Loops
You have a list of user records as dictionaries:
let users = [
  ["name": "Alice", "age": 25],
  ["name": "Bob", "age": 17],
  ["name": "Cara", "age": 30]
]

Using a for-in loop with a where clause, how do you print only the names of users who are 18 or older?
Afor user in users { if user["age"] >= 18 { print(user["name"]!) } }
Bfor user where (user["age"] as? Int ?? 0) >= 18 in users { print(user["name"]!) }
Cfor user in users if (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) }
Dfor user in users where (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) }
Step-by-Step Solution
Solution:
  1. Step 1: Use correct for-in where syntax

    The where clause must come after in users to filter users by age.
  2. Step 2: Check type casting and condition

    Use safe cast as? Int with default 0, then check if age >= 18.
  3. Step 3: Print the name safely

    Access user["name"]! to print the name string.
  4. Final Answer:

    for user in users where (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) } -> Option D
  5. Quick Check:

    Correct for-in where with safe cast [OK]
Quick Trick: Put where after in users with safe cast [OK]
Common Mistakes:
  • Placing where before in
  • Using if instead of where
  • Not casting age safely
  • Forgetting to unwrap name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes