Ben Ben - 5 years ago 99
Swift Question

Converting [Int?] to [Int]

I have a

, e.g.
that I'd like to convert to an array of
items i.e.

However, my code currently gives me a
instead (an array of optional integers). Here is the code:

let years = (item["years"] as! String)
.map { word in Int(word) }

I tried a few things, like changing
, and adding
to the end of
, but swift didn't like the look of those ideas.

I presume there's something obvious I'm doing wrong as a beginner, but I'm not quite sure what! Any help would be greatly appreciated - thank you!

Answer Source

A classic way to turn an array of optionals into an array of non optionals is flatMap { $0 }:

let years = { word in Int(word) }.flatMap { $0 }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download