Member-only story
Unwrap an Array of Optional Values Using Swift
If we aren’t interested in nil
Keywords and Terminology
Array: an ordered series of objects which are the same type (article)
compactMap: Returns an array containing the non-nil
results of calling the given transformation with each element of this sequence
Force unwrapping: A method in which an optional is forced to return a concrete value. If the optional is nil, this will cause a crash
Optionals: Swift introduced optionals that handle the absence of a value, simply by declaring if there is a value or not. An optional is a type on it’s own! (article)
The opportunity
In this example there is an Array of Strings
and nil
, that is an array of optionals because some of the values are Strings
and some are represented by nil
.
let arrayOfOptionals: [String?] = ["There", "Present", nil, "Not nil", nil, "Some"]
This is all fine — but what if you want to do something to each of these Strings using something like Mapping where we run the same function against every element in the array.
This can be written as:
let uppercaseArray = arrayOfOptionals.map{ $0?.uppercased() }
Now I’m not a big fan of the optional question mark ?
, and the reason for that becomes apparent when we print out this array
to the console (by running print(uppercaseArray)
):
[Optional("THERE"), Optional("PRESENT"), nil, Optional("NOT NIL"), nil, Optional("SOME")]
Oh my word! What a mess when printed to the console! What if I needed to present this data to the end user? This would be awful, right?
So this article is really about…

Ignore nil with compactMap
We don’t care about those nil
values in this example, effectively we want rid of…