3

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!

Ben
  • 4,707
  • 5
  • 34
  • 55

2 Answers2

8

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 }

Gwendal Roué
  • 3,949
  • 15
  • 34
  • 4
    You're right to use flatMap but then you can simplify like this : `let years = (item["years"] as! String) .componentsSeparatedByString(",") . flatMap { Int($0) }` – ebluehands Dec 30 '15 at 09:22
  • please, advice the need to import Foundation (componentsSeparatedByString). for 'pure' Swift see my answer – user3441734 Dec 30 '15 at 09:59
6

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]
user3441734
  • 16,722
  • 2
  • 40
  • 59
  • A nice clean alternative - just to help with my understanding of Swift, is there any particular advantage to avoiding Foundation, or is it just another option with the same result? – Ben Dec 30 '15 at 10:00
  • 2
    @Ben Foundation is available on apple platform. open source Foundation is not fully implemented at present time. i hope with Swift3.0 the situation will change for an advantage of the community. Even on apple platform sometimes is hard to see what is 'wrong' due to 'free bridging'. It is up to you, what do you prefer, I try to avoid Foundation as much as possible in my own code, at least for now. Also speed of pure Swift code could be better (depends on your implementation) – user3441734 Dec 30 '15 at 10:06