Assign if not nil; if nil, then assign

:  ~ 1 min read

I always found Ruby's ||= operator interesting, which says (roughly) assign the right hand side to the left hand side, if the latter is nil (or false). But what about assigning the right hand side to the left hand side, if the former is not nil?

Here's my take on these two, with rather intuitive operators (if you ask me, of course):

infix operator ??= // If left is nil, then assign
func ??=<T>(lhs: inout T?, rhs: T?) {
    guard lhs == nil else { return }
    lhs = rhs
}

infix operator =?? // Assign if right is not nil
func =??<T>(lhs: inout T, rhs: T?) {
    guard let rhs = rhs else { return }
    lhs = rhs
}

Now we can write:

var s1: String? = nil
var s2 = "s2"

s2 =?? s1 // s1 is nil, nothing happens
s1 ??= "first" // s1 is nil, assigns the string to it

s2 =?? s1 // s1 isn't nil, assigns s1's value to s2
s1 ??= "second" // s1 isn't nil, nothing happens