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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With