【问题标题】:How to write a text file consisting of double values into an array in Swift如何在 Swift 中将包含双精度值的文本文件写入数组
【发布时间】:2020-10-22 17:39:41
【问题描述】:

有谁知道如何在 Swift 中将文本文件的内容读入数组? 我在这里遇到了数据类型转换的问题,到目前为止,我找不到将包含双精度值的文件保存到数组中的方法。此外,这些值仅由换行符分隔。因此,数组的字段必须是单行。如何编写可以读取完整文本文件的自动查询?

文本文件中的数据集如下所示:

  • 0.123123
  • 0.123232
  • 0.344564
  • -0.123213 ...等等

【问题讨论】:

标签: arrays swift txt


【解决方案1】:

您可以在分隔符为新行的地方拆分字符串,然后 compactmap 将子字符串初始化为 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)
}

这假设您的数字前后没有空格。如果您需要确保双初始化器在这些情况下不会失败,您可以在初始化数字之前对其进行修剪:

let numbers = txt.split(whereSeparator: \.isNewline)
    .map { $0.trimmingCharacters(in: .whitespaces) }
    .compactMap(Double.init)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多