Recall & Review
beginner
What does the nil coalescing operator (??) do in Swift?
It provides a default value when an optional is nil. It unwraps the optional if it has a value, otherwise returns the default value.
Click to reveal answer
intermediate
How can you chain multiple nil coalescing operators?
You can chain them like: optional1 ?? optional2 ?? defaultValue. Swift evaluates from left to right and returns the first non-nil value.
Click to reveal answer
intermediate
Can the right side of the nil coalescing operator be another optional?
Yes, but the result will be an optional if the right side is optional. To get a non-optional result, the right side should be a non-optional value.
Click to reveal answer
beginner
Explain how nil coalescing operator helps avoid nested if-let statements.Instead of multiple nested if-let to unwrap optionals, you can use ?? to provide defaults and simplify code, making it cleaner and easier to read.Click to reveal answer
advanced
What happens if you use nil coalescing operator with a function call on the right side?
The function is only called if the left optional is nil. This is useful for lazy evaluation or expensive default value calculations.
Click to reveal answer
What will this Swift code print? <br> let a: Int? = nil <br> let b = a ?? 5
✗ Incorrect
Since 'a' is nil, the nil coalescing operator returns the default value 5.
Which of these is a valid use of chaining nil coalescing operators?
✗ Incorrect
Chaining like 'a ?? b ?? 10' is valid and returns the first non-nil value.
If 'a' is Int? and 'b' is Int?, what is the type of 'a ?? b'?
✗ Incorrect
If the right side is optional, the result remains optional.
When is the right side expression of '??' evaluated?
✗ Incorrect
The right side is evaluated only if the left side is nil, enabling lazy evaluation.
Which statement about nil coalescing operator is false?
✗ Incorrect
It does not always return a non-optional; if the right side is optional, the result can be optional.
Explain how the nil coalescing operator (??) works in Swift and give an example of chaining it with multiple optionals.
Think about how it picks the first non-nil value.
You got /3 concepts.
Describe a scenario where using the nil coalescing operator with a function call on the right side is beneficial.
Consider when the default value is expensive to compute.
You got /3 concepts.