Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 313
Moin Uddin Avatar asked Oct 15 '14 07:10

Moin Uddin


2 Answers

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
}
like image 62
danielbeard Avatar answered Nov 02 '22 03:11

danielbeard


Correct syntax in swift for String contentsOfFile is:

String(contentsOfFile: "String", encoding: "NSStringEncoding", error: "NSErrorPointer")
like image 4
Valentin Avatar answered Nov 02 '22 02:11

Valentin