Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a short text file to a string in swift

Tags:

swift

nsstring

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?

like image 418
Maury Markowitz Avatar asked Oct 26 '14 13:10

Maury Markowitz


2 Answers

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.

like image 173
David Reidy Avatar answered Sep 24 '22 07:09

David Reidy


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)
like image 36
Antonio Avatar answered Sep 23 '22 07:09

Antonio