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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters