Only assign new values when the right operand is not nil

It’s sometimes useful to create custom operators to avoid boilerplate code. For example in the following code, we check if a variable is not nil before assigning it to our object:

if let basedOn = basedOn {
    story.basedOn = basedOn
}

It would be much better if we could simplify and have this instead:

story.basedOn ?= basedOn

To do that in Swift, we can create an “Optional Assignment” custom operator, as short as ?= here, with a few lines of code:


Leave a Reply

Your email address will not be published. Required fields are marked *