【发布时间】:2019-02-24 02:21:22
【问题描述】:
我需要读取一个文本文件并将其转换为一个数组,以便可以使用它来填充 tableView。数组中一行中的每个键都将进入 tableView 单元格中的不同标签。
制表符分隔的文本数据结构看起来像这样,但有 120 行:
文本A 文本B 文本C 文本D
“TextA”进入labelA,“TextB”进入labelB,“TextC”进入labelC等等。
我有一些这样的工作。我可以阅读文本文件并按行分隔。我遇到问题的部分是用制表符分隔每一行并用键将其放入数组中。 for 循环内的部分是我遇到问题的地方。我不确定这是否是最好的方法。
我想我可以弄清楚如何将数组解析到 tableview 中,但我也可能会寻求帮助。
感谢您的帮助。
var figureArray = [String]()
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(gTheCollection).appendingPathExtension("txt")
do {
let readText = try String(contentsOf: fileURL, encoding: String.Encoding.utf8)
let theLines = readText.components(separatedBy: "\n")
let theCount = theLines.count - 1
for i in 0...(theCount) {
let figureData = theLines[i].components(separatedBy: "\t")
figureArray.append(figureData[0])
figureArray.append(figureData[1])
figureArray.append(figureData[2])
figureArray.append(figureData[3])
}
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
【问题讨论】:
-
您的问题到底是什么?
let figureData = theLines[i].components(separatedBy: "\t")行不行? -
是的,让 figureData = theLines[i].components(separatedBy: "\t") 确实有效。它将标签处的刺分开,但它只是使标签变成逗号。如果我打印 theLines 我得到: ["TextA\tTextB\tTextC\tTextD", "TextE\tTextF\tTextG\tTextH"] 如果我在代码运行后打印 figureArray,我得到: ["TextA", "TextB", " TextC”、“TextD”、“TextE”、“TextF”、“TextG”、“TextH”] 我认为问题在于我如何附加 figureArray。抱歉,我在解释问题时遇到了一些问题。
-
["TextA", "TextB", ... , "TextH"] (逗号分隔值)是 Swift 在终端中打印数组时使用的格式,所以听起来像你的代码实际上正在做你所期望的。