有谁知道如何在 Swift 中将文本文件的内容读入数组?我在此处遇到数据类型转换问题,到目前为止,我找不到将包含双精度值的文件保存到数组中的方法。此外,这些值仅由换行符分隔。因此,数组的字段必须是单行。如何编写可以读取完整文本文件的自动查询?
文本文件中的数据集如下所示:
- 0.123123
- 0.123232
- 0.344564
- -0.123213 ... 以此类推
您可以在分隔符为新行的地方拆分字符串,然后将子字符串初始化为 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)