DCDC DCDC - 7 months ago 40
iOS Question

Convert nested array of strings into nested array of doubles using functional programming

I'd like to convert nested array of strings into nested array of doubles

example:

let Strings = [["1.1", "1.2"],["2.1", "2.2"]]


to

let Doubles = [[1.1, 1.2],[2.1, 2.2]]


I tried

let Doubles = Strings.flatMap(){$0}.flatMap(){Double($0)}


but in this case I obtain one array of double values, how to keep this array nested?

EDIT:

Could you also elaborate why not using
map()
twice nor
flatMap()
twice? Why the right way to do this is to use
map
, then
flatMap
?

Answer

Given this

let strings = [["1.1", "1.2"], ["2.1", "2.2"]]

You can write

let doubles: [[Double]] = strings.map { elms -> [Double] in
    return elms.flatMap { Double($0) }
}

Shorter version

If you want a shorter version (slightly different from the other answers) then

let doubles = strings.map { $0.flatMap(Double.init) }