Question re Nil Coalescing Default Value

Hello all,

I have a question question regarding the "default value" used in nil coalescing. My tutorial book states the following about the topic:

“You use it when you want to get a value out of the optional no matter what — and in the case of nil, you’ll use a default value. This is called nil coalescing. Here’s how it works:

var optionalInt: Int? = 10
var mustHaveResult = optionalInt ?? 0”

Would I be correct in assuming then that the default value used in nil coalescing - which according to the book is provided in cases of an optional having a value of nil - should always be 0?

Please help, thank you!

Not necessarily; it depends what you’re doing with the value inside of the optional.

Also, this works for optionals of all types, not just integers. You might have an optional String, and a sensible default might be “No name” or “No address” depending on what you’re doing with the String.

1 Like

The ?? operator uses the value on its left if that's not nil and otherwise uses the value on its right. You can put whatever value you want on the right.

2 Likes

Thank you!

Terms of Service

Privacy Policy

Cookie Policy