1

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.

1
  • let doubleArray = locationString.map{$0.compactMap(Double.init)} Commented Aug 16, 2018 at 15:34

1 Answer 1

3

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 )) } }
Sign up to request clarification or add additional context in comments.

7 Comments

This seems correct, although for some reason when I try and print the data, the output is just [[], [], [], [], []] have any ideas as to why it is doing this?
Check your input. The Strings cannot have leading or trailing spaces. You could trim those as well if needed.
Yeah, I've just noticed something when printing the locationString after the data is appended. The data is not being separated by the comma which it should be, so for example the first element looks like this: [["55.949636-3.19108]] I believe this is most likely the cause, do you have any help to separate the data with a comma when it is appended?
What does the original input look like?
So the original input is pulled from some XML data, it is being pulled as a string (definitely my bad but at this point its easier to work around than change original code). The data is appended to the array with the following: locationString.append([myTrail.trailLatitude + myTrail.trailLongitude]) when you print the data of the locationString array it looks like this: [["55.949636-3.19108]]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.