David Balcher
David Balcher

Reputation: 35

Swift: Is there a more succinct way to write the "if let" block below?

   if let phone = participant.phone {
                participantObject["phone"] = phone
            } else { print("Did not add phone") }

I need to unwrap an "String?" and only make the assignment if the optional is not nil

Upvotes: 0

Views: 97

Answers (2)

vadian
vadian

Reputation: 285082

Since assigning a nil value to a Swift dictionary removes the key you can easily use this syntax:

participantObject["phone"] = participant.phone

unless you want to preserve an existing value. Then there is no better syntax than yours.


However if you want to assign an alternative value if phone is nil, use the nil coalescing operator.

participantObject["phone"] = participant.phone ?? "n/a"

Upvotes: 3

Tim Vermeulen
Tim Vermeulen

Reputation: 12562

You could simply use

participatnObject["phone"] = participant.phone

because this code will simply only set the value for the key "phone" if participant.phone isn't nil. The only difference is that this code will remove a previous value for the "phone" key, if it was there, which doesn't happen with your code.

If you also need to print a message if no assignment was done, then your code is quite optimal. This is slightly shorter though:

participatnObject["phone"] = participant.phone
if participant.phone == nil { print("Did not add phone") }

Upvotes: 2

Related Questions