gpt4 book ai didi

ios - 在 CSV 文件的新行中添加新数据

转载 作者:行者123 更新时间:2023-11-30 12:01:41 26 4
gpt4 key购买 nike

我想使用 https://github.com/yaslab/CSV.swift/issues 将数组中的数据添加到 CSV 文件中顺便说一句,他们建议的方式是每个新行都需要声明

try! csv.write(row: ["", ""])

例如,手动。

import Foundation
import CSV

let stream = OutputStream(toFileAtPath: "/path/to/file.csv", append: false)!
let csv = try! CSVWriter(stream: stream)

try! csv.write(row: ["id", "name"])
try! csv.write(row: ["1", "foo"])
try! csv.write(row: ["1", "bar"])

csv.stream.close()

无论如何,我需要让它根据数组内对象的数量自动创建一个新行。所以我通过将每个 csv 附加到数组中来更改它

    func saveCSVFiles() -> URL {
let itemList = objectNo
let fileManager = FileManager.default

let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
csvFile = documentDirectory.appendingPathComponent("\(fileName!).csv")
let path = csvFile

let stream = OutputStream(url: csvFile!, append: false)
let csv = try! [CSVWriter(stream: stream!)]
try! csv[0].write(row: ["name", "x", "y", "width", "height"])

for no in stride(from: 1, to: itemList.count, by: 1) {
try! csv[no].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
}
csv[itemList.count].stream.close()

print("yesss!", "\(fileName!)")
return path!
}

但每次我尝试保存它都会导致 fatal error :索引超出范围在线for循环上并且根本不保存

任何建议都会有帮助

最佳答案

Swift(以及大多数语言)中的数组是从零开始的。所以你希望 for 循环从 0 到 count-1。有一个内置构造,​​ ..< ,这非常适合:

for no in 0..< itemList.count {
try! csv[no].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
}

编辑

听起来您需要将 csv 数组索引为从 1 到 itemList.count ,以及从 0 到 itemList.count - 1 的所有其他数组。因此你可能应该使用

for no in 0..< itemList.count {
try! csv[no+1].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
}

(注意 +1 索引中的 csv 。)

关于ios - 在 CSV 文件的新行中添加新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47140598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com