0
0
Swiftprogramming~5 mins

Nil coalescing operator (??) in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe unwrapped value of the optional
BThe default value on the right
Cnil
DAn error
Which of these is a correct use of the nil coalescing operator?
Alet result = optionalValue ?? 5
Blet result = 5 ?? optionalValue
Clet result = optionalValue ? 5
Dlet result = optionalValue || 5
If you have 'let x: String? = nil', what is the value of 'let y = x ?? "Hello"'?
A"Hello"
Bnil
Cx
DAn error
Can the nil coalescing operator be chained like 'a ?? b ?? c'?
AYes, it returns the first non-nil value
BNo, it causes a syntax error
COnly if all are integers
DOnly if all are strings
What type must the right side of the nil coalescing operator have?
AThe same type as the unwrapped optional
BAny type
COnly optional types
DOnly String type
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.