Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call can throw, but errors cannot be thrown out of a property initializer

After updated to Swift 2.0, when NSFielManager is called, it has caused the following error. Could you tell me what is the problem?

let cachesDirectoryURL = NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

Error:

"Call can throw, but errors cannot be thrown out of a property initializer"

like image 217
Toshi Avatar asked Dec 04 '22 02:12

Toshi


2 Answers

If you are declaring this as global in a class you need to add prefix "try!" to value you are assigning.

like this

let cachesDirectoryURL = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
like image 90
Meesum Naqvi Avatar answered Dec 10 '22 12:12

Meesum Naqvi


Which means we have to catch the error that might be thrown, should problem occurs:

do
{
    let cachesDirectoryURL = try NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
}
catch let error as NSError
{
    print(error.localizedDescription)
}
like image 30
Unheilig Avatar answered Dec 10 '22 12:12

Unheilig