我已經使用 DataFrame 成功匯入了一個簡單的兩列 CSV 檔案。現在我想把每行中的兩個單元格變成字串。左側或右側偶爾會丟失一個值;見列印輸出。 桌子
當我嘗試使用 nil 單元格處理一行時,程式崩潰并顯示“致命錯誤:在展開可選值時意外發現 nil”
所以我的問題是,如何安全地將單元格轉換為字串(如果為 Nil,則為“”)?
完成下面的 ContentView 代碼,在此先感謝您的幫助。
import SwiftUI
import TabularData
struct ContentView: View {
@State var openFile = false
var body: some View {
VStack {
Button(action: {openFile.toggle()}, label: {
Text("Open")
})
}.fileImporter(
isPresented: $openFile,
allowedContentTypes: [.commaSeparatedText],
allowsMultipleSelection: false) { (result) in
do {
let fileURL = try result.get().first
if fileURL!.startAccessingSecurityScopedResource() {
print(fileURL!)
importTable(url: fileURL!)
}
fileURL!.stopAccessingSecurityScopedResource()
} catch {
print("Unable to read file contents")
print(error.localizedDescription)
}
}
}
func importTable(url: URL) {
var importerTable: DataFrame = [:]
let options = CSVReadingOptions(hasHeaderRow: false, delimiter: ",")
do {
importerTable = try DataFrame(
contentsOfCSVFile: url,
options: options)
} catch {
print("ERROR reading CSV file")
print(error.localizedDescription)
}
print("\(importerTable)")
importerTable.rows.forEach { row in
let leftString = row[0]! as! String
let rightString = row[1]! as! String
print("Left: \(leftString) Right: \(rightString)")
}
}
}
uj5u.com熱心網友回復:
背景關系非常不安全,任何fileImporter不小心寫的感嘆號都可能導致應用程式崩潰。
首先,您必須檢查fileURL并中止匯入,如果它是nil
guard let fileURL = try result.get().first else { return }
if fileURL.startAccessingSecurityScopedResource() {
print(fileURL)
importTable(url: fileURL)
}
fileURL.stopAccessingSecurityScopedResource()
如果拋出錯誤,則importTable不能繼續,并且必須檢查 CSV 檔案是否每行包含兩個專案。do - catch另一方面,String根據定義,CSV 的(強制)強制轉換String是多余的。
func importTable(url: URL) {
var importerTable: DataFrame = [:]
let options = CSVReadingOptions(hasHeaderRow: false, delimiter: ",")
do {
importerTable = try DataFrame(
contentsOfCSVFile: url,
options: options)
print("\(importerTable)")
importerTable.rows.forEach { row in
if row.count > 1 {
let leftString = row[0]
let rightString = row[1]
print("Left: \(leftString) Right: \(rightString)")
}
}
} catch {
print("ERROR reading CSV file")
print(error.localizedDescription)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471651.html
