Implementing Ruby’s ||= operator in Swift


Airspeed Velocity

A common idiom in Ruby is to assign a value to a variable only if that variable isn’t already set, using the ||= operator:

Swift doesn’t provide such an operator out of the box, but using some of the features of the language, it’s possible to implement one.

Simple first implementation

First let’s try implementing it just for string types:

Note the use of the @assignment attribute, and the inout parameter on the left-hand side, which is the variable being assigned to.

This works. If you try the following

the second assignment will have no effect on s.

Using generics to apply to any type

What about implementing this with generics, so it will work not just for String but for any type? That’s pretty simple:

Now you can use our ||= on any type optional type – String?, Int?, or any user-defined class.

Using @auto_closure to…

View original post 544 more words