swiftnull-coalescing-operator

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"


Solution

  • Such an operator was considered and rejected. Details can be found here.

    The rationale 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.


    The the original rationale is now at gmane.io. You can request access to the mailing list by searching for the "gmane.comp.lang.swift.evolution" group (partial credit to the user from the comments).