Ben Ben - 5 years ago 99
Swift Question

Converting [Int?] to [Int]

I have a

String
, e.g.
"7,8,9,10"
that I'd like to convert to an array of
Int
items i.e.
[Int]


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

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


I tried a few things, like changing
Int(word)
to
Int(word!)
, and adding
!
to the end of
String)
, 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 = ...map { word in Int(word) }.flatMap { $0 }

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