filter out nil values in an array of optional int in swift

You can use the compactMap() function to filter out nil values in an array of optional integers. Here's an example:

main.swift
let optionalInts: [Int?] = [1, 2, nil, 4, nil, 5]

let filteredInts = optionalInts.compactMap { $0 }

print(filteredInts) // [1, 2, 4, 5]
138 chars
6 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.swift
let optionalInts: [Int?] = [1, 2, nil, 4, nil, 5]

let filteredInts = optionalInts.filter { $0 != nil }.map { $0! }

print(filteredInts) // [1, 2, 4, 5]
153 chars
6 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