当我将代码更新为最新的Swift语法时,我在下面的代码中收到错误。
请帮助我找到解决方案。
答案 0 :(得分:2)
你必须写入do catch块,因为它会引发异常
do {
try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch {
}
您还可以按如下方式捕获错误:
do {
try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
print(error.description)
}
你也可以通过警卫和推迟:http://nshipster.com/guard-and-defer/这是swift中的新概念
答案 1 :(得分:1)
writeToFile方法抛出异常。使用此块
do {
try str.writeToFile(filename, atomically: true, encoding: NSUTF8StringEncoding)
}
catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
}
答案 2 :(得分:0)
要解决您的问题,请尝试使用try catch
构造。
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch
{
}
答案 3 :(得分:0)
函数writeToFilePath(path,atomically:,encoding :)不返回任何内容(它的返回类型为Void或()
),并且您试图将任何内容与布尔值进行比较。
第二个错误行解释了此例程如果失败则抛出错误。您需要使用Swift的错误处理机制来处理错误,而不是尝试将函数结果与bool进行比较。
答案 4 :(得分:0)
在Swift中,它不会再返回Bool。这是文档中的描述:
func writeToFile(_ path: String,
atomically useAuxiliaryFile: Bool,
encoding enc: UInt) throws
因为它会抛出错误,你应该尝试忽略这样的错误:
try! contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
或者你抓住并处理错误:
do {
try contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
} catch let error {
// handle error here
}
答案 5 :(得分:0)
以上答案都是正确的!这些调用可能会引发异常。
do {
contentsOfFile str.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
}
catch {
}