jeffhardie123
jeffhardie123

Reputation: 13

Convert a 2d array of strings to a 2d array of double swift

I have 2 arrays:

var locationString = [[String]]()
var doubleArray = [[Double]]()

The array data is appended after a parser has ran just in case you are wondering why there is no data.

Essentially I am trying to convert the locationString from string to double. I originally tried the following:

let doubleArray = locationString.map{ Double($0) }

but this does not seem to work as i get an error of:

Cannot invoke initializer for type 'Double' with an argument list of type ((String]))

Any help would be appreciated, thanks.

Upvotes: 1

Views: 536

Answers (1)

vacawama
vacawama

Reputation: 154603

Use map with compactMap map:

let doubleArray = locationString.map { $0.compactMap(Double.init) }

Example:

let locationString = [["1.2", "2.3"], ["3.4", "4.4", "hello"]]

let doubleArray = locationString.map { $0.compactMap(Double.init) }

print(doubleArray) // [[1.2, 2.3], [3.4, 4.4]]

The outer map processes each array of strings. The inner compactMap converts the Strings to Double and drops them if the conversion returns nil because the String is not a valid Double.


To trim leading and trailing whitespace in your Strings before converting to Double, use .trimmingCharacters(in: .whitespaces):

let doubleArray = locationString.map { $0.compactMap { Double($0.trimmingCharacters(in: .whitespaces )) } }

Upvotes: 3

Related Questions