Swift'Btring.Type'没有名为'stringWithContentsOfFile'的成员

Moi*_*din 12 swift

我无法从Swift中的.text文件中读取文本字符串.

我可以使用以下代码管理文件

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

但每当我尝试使用"String.stringWithContentsOfFile"读取文件时,我得到"'String.Type'没有名为'stringWithContentsOfFile'的成员".stringWithContentsOfFile也不会出现在自动完成中.

我正在使用Xcode 6.1 GM Seed 2.

我见过人们使用"stringWithContentsOfFile"在许多教程和堆栈溢出中从文件中读取文本,但为什么它对我不起作用?

dan*_*ard 17

尝试这样的事情:

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

Swift 2.2:

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

  • 感谢您帮助使用正确的语法.我不知道为什么Apple没有在这里更新他们的文档https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/clm/ NSString/stringWithContentsOfURL:usedEncoding:error:或者我正在查看错误的文档? (2认同)