Search code examples
iosswiftswift2nsfilemanager

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"


Solution

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