Cleaner way to filter nil in Swift array

flatMap() does the job:

let filtered = arrayOfAnimal.flatMap { $0 }

The closure (which is the identity here) is applied to all elements, and an array with the non-nil results is returned. The return type is [Animal] and no forced cast is needed.

Simple example:

let array: [Int?] = [1, nil, 2, nil, 3]
let filtered = array.flatMap { $0 }

print(filtered)            // [1, 2, 3]
print(type(of: filtered))  // Array<Int>

For Swift 4.1 and later, replace flatMap by compactMap.


Your code works, but there is a better way. Use the compactMap function.

struct Animal {}

let arrayOfAnimal: [Animal?] = [nil, Animal(), Animal(), nil]
let newArray: [Animal] = arrayOfAnimal.compactMap { $0 }

Tags:

Ios

Swift