moin uddin moin uddin - 11 months ago 41
Swift Question

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?


Try something like this:

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

Swift 2.2:

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