Nil Coalescing for Optionals in Debug Prints

KD Knowledge Diet
2 min readDec 9, 2024

--

In Swift, working with Optionals is a common practice, and debugging your code often involves printing the values of these Optionals. To simplify the process of printing Optionals with default values when they are `nil`, you can define a custom operator that allows for string interpolation with a default string value. In this guide, we’ll explore how to create and use the `???` operator for nil coalescing in debug prints with Optionals.

Defining the Custom Operator:

To create the `???` operator for nil coalescing, you can use the following code:

infix operator ???: NilCoalescingPrecedence
func ???<T>(
optionalValue: T?,
defaultValue: @autoclosure () -> String
) -> String {
optionalValue
.map { String(describing: $0) } ?? defaultValue()
}

Here’s what this code does:

1. It defines the custom operator `???` with `NilCoalescingPrecedence` precedence.

2. The `???` operator takes two parameters:
— `optionalValue`: The Optional value you want to print.
— `defaultValue`: An autoclosure that provides a default string value when the `optionalValue` is `nil`.

Using the Custom Operator:
Now that you’ve defined the custom operator, you can use it in your code to print Optionals with default values in debug statements. Here’s an example:

var url: URL?
// Assign a URL some time later
url = URL(string: "https://example.com")
print("The URL is \(url ??? "nil")")

In this code snippet:

- The `url` Optional is interpolated within the debug print statement using the `???` operator.
- If `url` is not `nil`, its value is converted to a String using `String(describing:)`. If it is `nil`, the default string `”nil”` is used.

The result of the `print` statement will be “The URL is https://example.com" if `url` has a value, or “The URL is nil” if `url` is `nil`.

Conclusion:

Creating a custom operator like `???` for nil coalescing in debug prints with Optionals can simplify your debugging process in Swift. It allows you to easily print the values of Optionals while providing a default string when they are `nil`. This customization enhances code readability and helps you identify issues more efficiently during development and debugging.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet