Toshi
Toshi

Reputation: 1303

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"

Upvotes: 6

Views: 10164

Answers (2)

Meesum Naqvi
Meesum Naqvi

Reputation: 186

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)

Upvotes: 12

Unheilig
Unheilig

Reputation: 16302

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)
}

Upvotes: 6

Related Questions