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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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?