Bird
0
0

What will be printed by the following Swift code?

medium📝 Predict Output Q13 of 15
Swift - Optionals
What will be printed by the following Swift code?
var name: String? = "Alice"
if let unwrappedName = name {
    print("Hello, \(unwrappedName)!")
} else {
    print("No name found.")
}
AHello, nil!
BNo name found.
COptional("Alice")
DHello, Alice!
Step-by-Step Solution
Solution:
  1. Step 1: Check the optional value

    The variable name contains the string "Alice", not nil.
  2. Step 2: Apply if let unwrapping

    Since name has a value, unwrappedName gets "Alice" and prints the greeting.
  3. Final Answer:

    Hello, Alice! -> Option D
  4. Quick Check:

    Optional with value prints unwrapped string [OK]
Quick Trick: If optional has value, if let block runs [OK]
Common Mistakes:
  • Printing optional directly instead of unwrapped
  • Confusing else block execution
  • Assuming nil prints as string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes