gpt4 book ai didi

xcode - Swift:将 .csv 导入为字符串

转载 作者:行者123 更新时间:2023-11-28 13:16:12 24 4
gpt4 key购买 nike

我正在使用 Swift 导入存储在项目中的 .csv 文件。但是,我总是得到错误

fatal error: unexpectedly found nil while unwrapping an Optional value

我尝试做同样的事情,但将其转换为 .txt 文件,但也失败了。但是,如果我只是将内容直接复制并粘贴到新的 .txt 文件中,它就可以工作。我只是想把它变成一个字符串,以便以后可以使用它。

let file = NSBundle.mainBundle().pathForResource("SL", ofType:"csv")
var text = String(contentsOfFile: file!, encoding: NSUTF8StringEncoding, error: nil)!
var rawStudents = text.componentsSeparatedByString("\n")

最佳答案

确保在将您的 csv 文件拖到您的项目后,如果需要选择复制到项目选项。您应该始终使用 if let 来安全地解包您的可选值。

var error:NSError?
if let fileUrl = NSBundle.mainBundle().URLForResource("SL", withExtension:"csv") {
if let text = String(contentsOfURL: fileUrl, encoding: NSUTF8StringEncoding, error: &error) {
let rawStudents = text.componentsSeparatedByString(",")
} else {
println("error reading file")
if let error = error {
println(error.description)
}

}
}

关于xcode - Swift:将 .csv 导入为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933119/

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