I need to read the contents of a short text file in my Swift program. I did this:
var err: NSError?
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("cards", ofType: "ini")
let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
My problem is that I can't use the error reporting. If I change that last line to this:
let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: err)
The compiler complains "Extra argument 'contentsOfFile' in call". That makes zero sense to me, maybe someone else can figure it out?
Following the new error handling introduced into iOS 9/Swift 2, a solution for this that works for me is:
let fileLocation = NSBundle.mainBundle().pathForResource("filename", ofType: "txt")!
let text : String
do
{
text = try String(contentsOfFile: fileLocation)
}
catch
{
text = ""
}
text will contain the file contents or be empty in the case of an error.
At a first glance I'd say that you have to pass the err
variable by reference:
let content = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With