调用可以抛出,但不能从 属性 初始值设定项中抛出错误
Call can throw, but errors cannot be thrown out of a property initializer
更新到Swift 2.0后,调用NSFielManager
时出现如下错误。你能告诉我问题是什么吗?
let cachesDirectoryURL = NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
错误:
"Call can throw, but errors cannot be thrown out of a property
initializer"
这意味着如果出现问题,我们必须捕获可能抛出的错误:
do
{
let cachesDirectoryURL = try NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
}
catch let error as NSError
{
print(error.localizedDescription)
}
如果您在 class 中将其声明为全局变量,则需要为您分配的值添加前缀 "try!"。
像这样
let cachesDirectoryURL = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
更新到Swift 2.0后,调用NSFielManager
时出现如下错误。你能告诉我问题是什么吗?
let cachesDirectoryURL = NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
错误:
"Call can throw, but errors cannot be thrown out of a property initializer"
这意味着如果出现问题,我们必须捕获可能抛出的错误:
do
{
let cachesDirectoryURL = try NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
}
catch let error as NSError
{
print(error.localizedDescription)
}
如果您在 class 中将其声明为全局变量,则需要为您分配的值添加前缀 "try!"。
像这样
let cachesDirectoryURL = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)