简体   繁体   中英

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.

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 String s 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 String s before converting to Double , use .trimmingCharacters(in: .whitespaces) :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM