Bird
0
0

Which of the following Swift code snippets correctly uses the nil coalescing operator to assign a non-optional string to result?

easy📝 Syntax Q3 of 15
Swift - Optionals
Which of the following Swift code snippets correctly uses the nil coalescing operator to assign a non-optional string to result?
Alet result = optionalString ?? "Default"
Blet result = optionalString ? "Default"
Clet result = optionalString ?: "Default"
Dlet result = optionalString || "Default"
Step-by-Step Solution
Solution:
  1. Step 1: Recognize correct nil coalescing usage

    The operator ?? is used to provide a default value if the optional is nil.
  2. Step 2: Validate each option

    Only let result = optionalString ?? "Default" uses ?? correctly; others use invalid or different operators.
  3. Final Answer:

    let result = optionalString ?? "Default" -> Option A
  4. Quick Check:

    Correct nil coalescing syntax [OK]
Quick Trick: Use ?? to assign default when optional is nil [OK]
Common Mistakes:
  • Using ?: which is not Swift
  • Using ternary operator incorrectly
  • Using logical OR instead of nil coalescing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes