Overload the '??' Nil-Coalescing Operator for Custom Swift Types
Written by Team Kodeco
Written by Team Kodeco
The ??
operator in Swift is used for performing a nil-coalescing operation, which returns the left operand if it’s not nil
, otherwise it returns the right operand. When working with custom types in Swift, you may want to overload the ??
operator to perform a similar operation specific to your custom type.
Here’s an example of how you might overload the ??
operator for a custom OptionalString
class:
class OptionalString {
var value: String?
init(_ value: String?) {
self.value = value
}
}
extension OptionalString {
static func ?? (left: OptionalString, right: OptionalString) -> OptionalString {
return OptionalString(left.value ?? right.value)
}
}
Here’s an example of how you might use the overloaded ??
operator on the OptionalString
class:
let left = OptionalString("Hello")
let right = OptionalString(nil)
let result = right ?? left
print(result.value!) // Prints "Hello"
Prev chapter
8.
Overload the Prefix & Postfix Operators for Custom Swift Types
Next chapter
10.
Overload the '&&' AND & '||' OR Operators for Custom Swift Types