Swift Language Arrays Extracting values of a given type from an Array with flatMap(_:)

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


The things Array contains values of Any type.

let things: [Any] = [1, "Hello", 2, true, false, "World", 3]

We can extract values of a given type and create a new Array of that specific type. Let's say we want to extract all the Int(s) and put them into an Int Array in a safe way.

let numbers = things.flatMap { $0 as? Int }

Now numbers is defined as [Int]. The flatMap function discard all nil elements and the result thus contains only the following values:

[1, 2, 3]

Got any Swift Language Question?