Extracting values of a given type from an Array with flatMap
suggest changeThe 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 }
numbers is [Int]. This flatMap drops every nil. Swift 4.1 renamed that overload to compactMap; flatMap now flattens a sequence of sequences. The result contains only:
[1, 2, 3]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents