Bird
0
0

What will be printed by the following Swift code?

medium📝 Predict Output Q4 of 15
Swift - Optionals
What will be printed by the following Swift code?
let optionalGreeting: String? = "Hello"
let greeting = optionalGreeting ?? "Hi"
print(greeting)
AOptional("Hello")
BHi
Cnil
DHello
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate the optional value

    The variable optionalGreeting contains the string "Hello", so it is not nil.
  2. Step 2: Apply the nil coalescing operator

    The expression optionalGreeting ?? "Hi" returns the value of optionalGreeting because it is not nil.
  3. Final Answer:

    Hello -> Option D
  4. Quick Check:

    Non-nil optional returns its value [OK]
Quick Trick: If left side is non-nil, ?? returns it [OK]
Common Mistakes:
  • Assuming it prints the default value even if optional is non-nil
  • Confusing optional value with its wrapped string
  • Expecting 'Optional("Hello")' instead of unwrapped string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes