Deco Deco - 2 years ago 77
Swift Question

Can I use Optional chaining to give a default value for the property of an optional?

Is it possible to use optional chaining and nil coalescing simultaneously like so?

print("Meeting host: " + ?? “No host”)

I'd like to do this but I get an error saying that my String? is not unwrapped.
is a non optional String.

Is this possible without having to unwrap
before hand and if not why does my attempt at doing this not work?

Answer Source

You don't have to unwrap it to get it to work. That is not why the error occurred. The ?? is designed to handle such cases, after all.

The error occurs because of operator precedence. The compiler thinks that it should evaluate the + first, concatenating the two strings, THEN do the nil-coalescing. It sees that the second operand is not unwrapped and complains.

To make it produce the intended result, explicitly tell the compiler to evaluate the ?? first by adding brackets:

print("Meeting host: " + ( ?? “No host”))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download