Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q4 of 15
Swift - Control Flow
What will be the output of this Swift code?
func greet(_ name: String?) {
    guard let name = name else {
        print("No name provided")
        return
    }
    print("Hello, \(name)!")
}
greet(nil)
greet("Anna")
ANo output
BHello, nil!\nHello, Anna!
CHello, Anna!\nNo name provided
DNo name provided\nHello, Anna!
Step-by-Step Solution
Solution:
  1. Step 1: Analyze guard behavior with nil input

    When name is nil, the guard fails, prints "No name provided", and returns early.
  2. Step 2: Analyze guard behavior with non-nil input

    When name is "Anna", guard passes and prints "Hello, Anna!".
  3. Final Answer:

    No name provided\nHello, Anna! -> Option D
  4. Quick Check:

    Guard unwraps optional or exits early [OK]
Quick Trick: Guard unwraps optionals or exits early with else [OK]
Common Mistakes:
  • Assuming guard prints 'Hello, nil!'
  • Ignoring early return on guard failure
  • Mixing output order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes