-1

Does anyone know how it is possible in Swift to read the contents of a text file into an array? I'm having problems with the data type conversion here and so far I can't find a way to save a file that consists of double values into an array. In addition, the values are only separated by line breaks. So a field of an array would have to be a single row. How can I write an automated query that can read a complete text file?

The dataset in the text file looks like this:

  • 0.123123
  • 0.123232
  • 0.344564
  • -0.123213 ... and so on
  • Check if this helps: https://stackoverflow.com/questions/29217554/swift-text-file-to-array-of-strings – algo_user Oct 22 '20 at 17:44
  • Does this answer your question? [Swift Text File To Array of Strings](https://stackoverflow.com/questions/29217554/swift-text-file-to-array-of-strings) – Joakim Danielson Oct 22 '20 at 18:37
  • Sorry, but these two cases do not deal with the problem of data types. In these cases, the text file is divided into strings. However, I need these as doubles. – Hannes Broschk Jan 29 '21 at 11:13

1 Answers1

1

You can split your string where separator is new line and then compactmap initialising the substrings into Double:

let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    .appendingPathComponent("file.txt")
// or if the file is located in you bundle directory
// let url = Bundle.main.url(forResource: "file", withExtension: "txt")!
do {
    let txt = try String(contentsOf: url)
    let numbers = txt.split(whereSeparator: \.isNewline)
                      .compactMap(Double.init) // [0.123123, 0.123232, 0.344564, -0.123213]
} catch {
    print(error)
}

This assumes there is no spaces before or after your numbers. If you need to make sure the double initializer will not fail in those cases you can trim them before initialising your numbers:

let numbers = txt.split(whereSeparator: \.isNewline)
    .map { $0.trimmingCharacters(in: .whitespaces) }
    .compactMap(Double.init)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571