-2

I need to parse four comma-separated values of Double type from a single string (e.g. "0.0100, 2.0200, 0.10, 0.000"). The string length is unknown, has no specific terminator, and contains values with a different number of characters. This would be so simple in C but not being exactly fluent in Swift, is causing me a great deal of discomfort. Is there an elegant way to do this in Swift? If so, please give an example.

bbabbitt
  • 3
  • 3
  • `.components(separatedBy: ", ")`? – Sweeper Sep 05 '19 at 20:31
  • First https://stackoverflow.com/questions/25678373/split-a-string-into-an-array-in-swift, then https://stackoverflow.com/questions/51507121/convert-array-of-string-into-double-in-swift . It's all one line of code when done. – rmaddy Sep 05 '19 at 20:32

1 Answers1

0

As mentioned by Sweeper and rmaddy, it's just one line of code, you can do it like this:

let commaSeparatedString = "0.0100, 2.0200, 0.10, 0.000"
let doubleValuesArray = commaSeparatedString.components(separatedBy: ", ").map { Double($0) } // [Optional(0.01), Optional(2.02), Optional(0.1), Optional(0.0)]

They are optionals because mapping a string to double may fail. If you want your doubleValuesArray to only contain non-optional values, you can use compactMap instead of map. Like this:

let doubleValuesArray = commaSeparatedString.components(separatedBy: ", ").compactMap { Double($0) } // [0.01, 2.02, 0.1, 0.0]
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
  • Wow! I had no idea there would be something as simple and powerful as commaSeparatedString.components(). Where can I find API documentation for powerful methods/functions like this? – bbabbitt Sep 08 '19 at 23:51