调用可以抛出,但错误不能从属性初始值设定项中抛出

lal*_*ala 4 nsfilemanager ios swift swift2

更新到Swift 2.0后,NSFielManager调用时,出现如下错误。你能告诉我有什么问题吗?

let cachesDirectoryURL = NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
Run Code Online (Sandbox Code Playgroud)

错误:

“调用可以抛出,但错误不能从属性初始值设定项中抛出”

Mee*_*qvi 10

如果您在类中将其声明为全局,则需要添加前缀“try!” 来分配你的价值。

像这样

let cachesDirectoryURL = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
Run Code Online (Sandbox Code Playgroud)


Unh*_*lig 6

这意味着我们必须捕获出现问题时可能引发的错误:

do
{
    let cachesDirectoryURL = try NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
}
catch let error as NSError
{
    print(error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)