Moin Uddin
Moin Uddin

Reputation: 349

Swift 'String.Type' does not have a member named 'stringWithContentsOfFile'

I am having trouble to read text string from .text file in Swift.

I could manage to write file using following code

var writeError: NSError?
let theFileToBeWritten = theStringWillBeSaved.writeToFile(pathToTheFile, atomically: true, encoding: NSUTF8StringEncoding, error: &writeError);

But whenever I try to read the file using "String.stringWithContentsOfFile", I get "'String.Type' does not have a member named 'stringWithContentsOfFile'". stringWithContentsOfFile also does not appear in autocomplete.

I am using Xcode 6.1 GM Seed 2.

I have seen people using "stringWithContentsOfFile" to read text from file in many tutorials and stack overflow but why is it not working for me?

Upvotes: 12

Views: 6385

Answers (3)

danielbeard
danielbeard

Reputation: 9149

Try something like this:

var error:NSError?
let string = String(contentsOfFile: "/usr/temp.txt", encoding:NSUTF8StringEncoding, error: &error)
if let theError = error {
   print("\(theError.localizedDescription)")
}

Swift 2.2:

if let string = try? String(contentsOfFile: "/usr/temp.txt") {
  // Do something with string
}

Upvotes: 17

Valentin
Valentin

Reputation: 3302

Correct syntax in swift for String contentsOfFile is:

String(contentsOfFile: "String", encoding: "NSStringEncoding", error: "NSErrorPointer")

Upvotes: 4

Rein rPavi
Rein rPavi

Reputation: 3396

you can do it like this

var error : NSError?
var myFileContent = String()
myFileContent = NSString.stringWithContentsOfFile("yourFilePath", encoding: NSUTF8StringEncoding, error: &error)
if let optionalError = error{
    println("\(optionalError.localizedDescription)")
}

Upvotes: 0

Related Questions