conditionally flatten nested arrays in swift

To conditionally flatten a nested array, you can use flatMap(_:) method in Swift:

main.swift
let nestedArray = [[1, 2, 3], [4, 5, 6], [], [7, 8, 9], []]
let flattenedArray = nestedArray.flatMap { $0.isEmpty ? nil : $0 }
print(flattenedArray)
149 chars
4 lines

In the above code, we are using flatMap(_:) to flatten the nested array, and using a condition to skip empty arrays. By returning nil from the closure for empty arrays, we are effectively removing them from the flattened array.

The output of the above code will be:

main.swift
[1, 2, 3, 4, 5, 6, 7, 8, 9]
28 chars
2 lines

This technique can be used with any condition for filtering elements from the nested arrays.

gistlibby LogSnag