在swift中将短文本文件读取到字符串

Mau*_*itz 14 nsstring swift

我需要在Swift程序中读取短文本文件的内容.我这样做了:

var err: NSError?
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("cards", ofType: "ini")
let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
Run Code Online (Sandbox Code Playgroud)

我的问题是我无法使用错误报告.如果我将最后一行更改为:

let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: err)
Run Code Online (Sandbox Code Playgroud)

编译器在调用中抱怨"额外参数'contentsOfFile'.这对我来说没有任何意义,也许其他人可以解决这个问题?

小智 18

在iOS 9/Swift 2中引入新的错误处理之后,对我有用的解决方案是:

let fileLocation = NSBundle.mainBundle().pathForResource("filename", ofType: "txt")!
let text : String
do
{
    text = try String(contentsOfFile: fileLocation)
}
catch
{
    text = ""
}
Run Code Online (Sandbox Code Playgroud)

text将包含文件内容,或者在出错时为空.


Ant*_*nio 14

乍一看,我会说你必须err通过引用传递变量:

let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err)
Run Code Online (Sandbox Code Playgroud)