Bird
0
0

Identify the error in this Swift code using nil coalescing:

medium📝 Debug Q14 of 15
Swift - Operators and Expressions
Identify the error in this Swift code using nil coalescing:
let x: Int? = nil
let y: Int = 3
let z = x ?? y ?? 5
print(z)
Ax must be non-optional
BNo error, code runs fine
Cy must be optional to use ??
DCannot use ?? with non-optional y
Step-by-Step Solution
Solution:
  1. Step 1: Understand the types involved in nil coalescing

    The operator ?? requires the right side to be the same type as the optional or a non-optional fallback value.
  2. Step 2: Analyze the expression x ?? y ?? 5

    Here, x is Int?, y is Int, but y ?? 5 is invalid because y is not optional, so you cannot use ?? on it.
  3. Final Answer:

    Cannot use ?? with non-optional y -> Cannot use ?? with non-optional y
  4. Quick Check:

    Right side of ?? must be optional or value [OK]
Quick Trick: Right side of ?? must be optional or value, not non-optional with ?? [OK]
Common Mistakes:
  • Using ?? on non-optional values
  • Confusing optional and non-optional types
  • Assuming ?? works like || operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes