ma11hew28 ma11hew28 - 3 years ago 103
Swift Question

Does Swift have an “or equals” function like ||= in Ruby?

In Swift, how do I set an optional

foo
but only if it's
nil
?

I know about Swift's nil coalescing operator:

foo = foo ?? "Hello"
(where
foo
is an optional
String
)

But, is there a better way, like in Ruby?

foo ||= "Hello"

Answer Source

Such an operator was considered and rejected: https://github.com/apple/swift-evolution/blob/master/proposals/0024-optional-value-setter.md

The rational behind the rejection is supposed to be in the swift-evolution email list, but the link attached to the above points to SE-0025 instead of 24.

Here is the link to the rational (Edited because of Kenneth Bruno's comment blow): http://article.gmane.org/gmane.comp.lang.swift.evolution/7694

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download