Bird
0
0

Which of the following best describes the behavior of this Swift code?

easy📝 Conceptual Q2 of 15
Swift - Loops
Which of the following best describes the behavior of this Swift code?
let names = ["Anna", "Bob", "Cindy", "David"]
for name in names where name.count == 4 {
    print(name)
}
APrints all names longer than 4 letters
BPrints all names regardless of length
CPrints all names shorter than 4 letters
DPrints all names with exactly 4 letters
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the where condition

    The condition name.count == 4 filters names with exactly 4 letters.
  2. Step 2: Check which names match

    "Anna" (4), "Bob" (3), "Cindy" (5), "David" (5), so only "Anna" prints.
  3. Final Answer:

    Prints all names with exactly 4 letters -> Option D
  4. Quick Check:

    Filter by length == 4 = Prints matching names [OK]
Quick Trick: Count characters to filter strings with where [OK]
Common Mistakes:
  • Assuming it prints all names
  • Confusing == with > or <
  • Ignoring the where clause

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes