0

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
3
  • Check if this helps: stackoverflow.com/questions/29217554/… Commented Oct 22, 2020 at 17:44
  • Does this answer your question? Swift Text File To Array of Strings Commented Oct 22, 2020 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. Commented Jan 29, 2021 at 11:13

1 Answer 1

2

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

Comments

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.