Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q13 of 15
Swift - Optionals
What will be the output of this Swift code?
var name: String? = "Alice"
print(name)
Anil
BAlice
COptional("Alice")
DError: Cannot print optional directly
Step-by-Step Solution
Solution:
  1. Step 1: Understand printing an optional variable

    When printing an optional variable directly, Swift shows it wrapped as Optional(value) if it has a value.
  2. Step 2: Check the variable value

    The variable name holds the string "Alice", so printing it shows Optional("Alice").
  3. Final Answer:

    Optional("Alice") -> Option C
  4. Quick Check:

    Printing optional shows Optional(value) [OK]
Quick Trick: Printing optional shows Optional(...) wrapper [OK]
Common Mistakes:
  • Expecting direct value without Optional()
  • Assuming printing optional causes error
  • Confusing nil with a string value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes