You can use the compactMap()
function to filter out nil values in an array of optional integers. Here's an example:
main.swift138 chars6 lines
In the code above, we define an array optionalInts
that contains a mix of non-nil integers and nil
values. We then call the compactMap()
function on this array and pass it a closure that simply returns the optional value itself (using the shorthand $0
syntax).
The compactMap()
function then creates a new array containing only the non-nil values from the original array, and returns that array. We've assigned this result to a new constant filteredInts
, and printed it to the console to verify that it contains only the non-nil integers.
Note that we could have achieved the same result using the filter()
function in combination with the nil-coalescing operator (??
):
main.swift153 chars6 lines
However, the compactMap()
approach is more concise and arguably more readable, since it avoids the need for explicit nil
checks and force-unwrapping of optionals.
gistlibby LogSnag