Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2016-06-24

Nil coalescing assignment | A nifty Swift addition

Just a little thing, but then again its the little things that can make life worth while.... especially as a programmer.

So, how often do you find yourself writing code like:

if str == nil { str = "Some text" }

Or the slightly better looking:

str = str ?? "Some text"

But I think it should be still shorter, what about:

str ??= "Some text"


Well, turns out that is quite possible in Swift with the following:

infix operator ??= {}

func ??=<T> (inout lhs: T?, rhs: T) {
    if lhs == nil { lhs = rhs }

}

Just include the above lines in your project, and you're set.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment