Declan McKenna
Declan McKenna

Reputation: 4910

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?

Upvotes: 4

Views: 3576

Answers (2)

Oleg Danu
Oleg Danu

Reputation: 4159

There is an easier solution for this:

class Host {
    var email: String?
}

var host: Host? = nil
print("Meeting host: " + String(describing: host?.email))

The output is:

Meeting host: nil

Upvotes: 1

Sweeper
Sweeper

Reputation: 272845

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”))

Upvotes: 7

Related Questions