Deco Deco - 1 year ago 56
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: " + meeting.host?.email ?? “No host”)


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

Is this possible without having to unwrap
host
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: " + (meeting.host?.email ?? “No host”))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download