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

标签 ios arrays swift csv for-loop

我想使用 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/

相关文章:

c - 写入文件问题

arrays - Swift 如何使用带有索引 [i] 的 for 循环读取数组的所有索引

arrays - Swift 中带有数组的 For-In 循环中迭代器元素的可变性

ios - 在 UIScrollView 中居中 UILabel

ios - 调用 collectionView(_ :layout:sizeForItemAt:) in Swift 4

iphone - 在 Objective-C 中使用 WebSocket

java - 快速查找数组中元素的数量

ios - webview后如何返回应用程序?

ios - RxAlamofire: retryWhen 掉进订阅 block

ios - 访问另一个应用程序的 CloudKit 数据库?