Ben
Ben

Reputation: 4867

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!

Upvotes: 3

Views: 106

Answers (2)

user3441734
user3441734

Reputation: 17572

pure Swift solution, without help of Foundation

let arr = "7,8,9,10".characters.split(",").flatMap{ Int(String($0)) }
print(arr) // [7, 8, 9, 10]

Upvotes: 6

Gwendal Roué
Gwendal Roué

Reputation: 4044

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 }

Upvotes: 8

Related Questions