Extracting values of a given type from an Array with flatMap

suggest change

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]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents