0
0
Swiftprogramming~5 mins

Nil coalescing operator deep usage 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. 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
A5
Bnil
C0
DCompilation error
Which of these is a valid use of chaining nil coalescing operators?
Alet x = a ?? b ?? 10
Blet x = a ?? ?? 10
Clet x = ?? a ?? 10
Dlet x = a ?? b ??
If 'a' is Int? and 'b' is Int?, what is the type of 'a ?? b'?
ACompilation error
BInt
COptional<Optional<Int>>
DInt?
When is the right side expression of '??' evaluated?
AOnly if the left side is non-nil
BOnly if the left side is nil
CNever
DAlways
Which statement about nil coalescing operator is false?
AIt unwraps optionals or returns a default value
BIt can chain multiple optionals
CIt always returns a non-optional value
DIt evaluates the right side lazily
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.