Unwrap an Array of Optional Values Using Swift

If we aren’t interested in nil

Steven Curtis
3 min readApr 28, 2022

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.

--

--

No responses yet