gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:26:03 25 4
gpt4 key购买 nike

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

我可以用下面的代码写文件

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

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

我正在使用 Xcode 6.1 GM Seed 2。

我在许多教程和堆栈溢出中看到有人使用“stringWithContentsOfFile”从文件中读取文本,但为什么它对我不起作用?

最佳答案

尝试这样的事情:

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
}

关于Swift 'String.Type' 没有名为 'stringWithContentsOfFile' 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26376698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com