Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil-Coalescing Operator without changing value [duplicate]

Nil-Coalescing Operators are one of my favorite things about Swift. Since becoming quite familiar with Swift, I've run into a few different special cases. One is where I want to assign an Optional value to a variable if it exists, otherwise, do nothing. I currently see two ways of doing this:

var a : String?
var b : String?

// Possibly assign a non-nil value to a and/or b

/* First Way */
a = b ?? a

/* Second Way */
if let b = b {
    a = b
}

In this context, it seems like the first way is probably fine, but when variables get much longer names like mapViewController.destinationCardTitle, the first way can get pretty long. I also can't just assign the value of a to nil or an empty String because if it already contains a non-nil value and b = nil, I don't want to change the value of a.

I'm wondering if there is a way to basically do the following without writing a twice.

a = b ?? a
like image 768
ZGski Avatar asked Mar 27 '26 02:03

ZGski


1 Answers

You can design your own infix operator:

infix operator ?=
func ?=<T>(lhs: inout T, rhs: T?) {
    lhs = rhs ?? lhs
}

var a = "a"
var b: String? = "b"

a ?= b

print(a)  // "b\n"
like image 175
Leo Dabus Avatar answered Apr 01 '26 06:04

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!