Non-nested appending of optionals to an Array

05. January 2017 blog 0

I like to prevent nested code as much as possible. In some cases though, it might not be very easy to do this. Consider the following code that adds a String to an Array:

this simple unwrapping of an optional seems trivial but wouldn’t a non-nested version look even nicer? That’s why I wrote a tiny Array extension that allow you to write it like this:

This moves the unwrapping of the optional to the append function itself. I also added a function that takes a second optional array as a parameter and a function that takes a condition which must be fulfilled before the element is added to the Array.

Here is the full code of this extension: