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 {
print("\(theError.localizedDescription)")
}
Swift 2.2:
if let string = try? String(contentsOfFile: "/usr/temp.txt") {
// Do something with string
}
Correct syntax in swift for String contentsOfFile is:
String(contentsOfFile: "String", encoding: "NSStringEncoding", error: "NSErrorPointer")
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