Bird
0
0

Consider this function that uses guard let inside a loop:

hard📝 Application Q9 of 15
Swift - Optionals
Consider this function that uses guard let inside a loop:
func printNames(_ names: [String?]) {
    for name in names {
        guard let validName = name else {
            print("Invalid name")
            continue
        }
        print(validName)
    }
}
printNames(["Anna", nil, "Bob"])

What will be the output?
AInvalid name\nInvalid name\nInvalid name
BAnna\nBob
CAnna\nInvalid name\nBob
DAnna\nInvalid name
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop with guard let

    For each name, guard let unwraps or prints "Invalid name" and continues to next iteration.
  2. Step 2: Trace output for input array

    "Anna" unwraps and prints, nil triggers "Invalid name", "Bob" unwraps and prints.
  3. Final Answer:

    Anna\nInvalid name\nBob -> Option C
  4. Quick Check:

    guard let with continue skips invalid optionals [OK]
Quick Trick: Use continue in guard else to skip invalid loop items [OK]
Common Mistakes:
  • Assuming loop stops on nil
  • Expecting no output for nil
  • Confusing continue with return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes