---
title: "Assign if not nil; if nil, then assign"
slug: assign-if-not-nil-if-nil-then-assign
section: tech
date: 2017-01-20T16:01:00.000Z
canonical: https://roland.leth.ro/blog/tech/assign-if-not-nil-if-nil-then-assign
---

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

```swift
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:

```swift
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
```