Recall & Review
beginner
What does the nil coalescing operator (??) do in Swift?
It provides a default value when an optional is nil. If the optional has a value, it unwraps and returns it; otherwise, it returns the default value.
Click to reveal answer
beginner
How would you use the nil coalescing operator to assign a default name if a variable 'username' is nil?
You write: let name = username ?? "Guest". This means if 'username' is nil, 'name' will be "Guest".Click to reveal answer
beginner
True or False: The nil coalescing operator (??) can only be used with optional values.
True. It is designed to work with optionals to provide a fallback value when the optional is nil.
Click to reveal answer
beginner
What is the result of this Swift code? <br><pre>let a: Int? = nil<br>let b = a ?? 10</pre>The value of 'b' will be 10 because 'a' is nil, so the nil coalescing operator returns the default value 10.
Click to reveal answer
intermediate
Explain why nil coalescing operator (??) is useful in real-life programming.
It helps avoid crashes by safely unwrapping optionals and providing a fallback value, making code simpler and safer when dealing with missing data.
Click to reveal answer
What does the nil coalescing operator (??) return if the optional on the left is not nil?
✗ Incorrect
If the optional has a value, the operator returns that value instead of the default.
Which of these is a correct use of the nil coalescing operator?
✗ Incorrect
The operator is used as 'optional ?? defaultValue'.
If you have 'let x: String? = nil', what is the value of 'let y = x ?? "Hello"'?
✗ Incorrect
Since x is nil, y gets the default string "Hello".
Can the nil coalescing operator be chained like 'a ?? b ?? c'?
✗ Incorrect
You can chain it to check multiple optionals and get the first non-nil value.
What type must the right side of the nil coalescing operator have?
✗ Incorrect
The default value must match the type of the optional's unwrapped value.
Describe how the nil coalescing operator (??) works in Swift and give a simple example.
Think about how to handle missing values safely.
You got /3 concepts.
Why is using the nil coalescing operator better than force unwrapping optionals?
Consider what happens if the optional is nil.
You got /4 concepts.