nil
coalescing operator is never evaluated as it's in RHS SW-R1010Using the nil coalescing operator (??
) in Swift can be helpful to provide
default values when dealing with optional types. However, it can be easy to
fall into the trap of using it unnecessarily, leading to redundant code that
can make the codebase harder to maintain and understand.
To fix this issue, remove the redundant nil
inside the nil coalescing
operator. Ensure that the default value provided by the operator is meaningful
and appropriate for the context in which it is being used.
Consider the following example:
In this case, y
will be assigned the value 0
if x
is nil
, which is a
more meaningful default value than nil
.
let x: Int? = nil
let y = x ?? nil
In this example, the nil
in the second line is redundant, as the ??
operator will already return nil
if x
is nil
. This can be simplified to:
let x: Int? = nil
let y = x ?? 0