5

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"

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Toshi
  • 1,293
  • 3
  • 19
  • 37
  • *Search* for error messages - http://stackoverflow.com/questions/30776458/call-can-throw-but-errors-can-not-be-thrown-out-of-a-global-variable-initialize , http://stackoverflow.com/questions/30786877/avaudioplayer-no-longer-working-in-swift-2-0-xcode-7-beta There is nothing 'special' with this code. – user2864740 Sep 26 '15 at 04:58

2 Answers2

12

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)
Meesum Naqvi
  • 186
  • 3
  • 9
6

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)
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
  • This still 'throws the error' out of the *property* initializer - and is otherwise invalid in context. The `let` in this case refers to a member, as indicated by the message, not a local binding. – user2864740 Sep 26 '15 at 04:56
  • It must be 1) a property, and; 2) under Swift 2 to reproduce the OPs behavior. This code makes no sense in context of *property* declarations. – user2864740 Sep 26 '15 at 05:01
  • @Unheilig http://swiftstub.com/601877219/ - context is wrong for the reported error. If you can show this working for a *property* created in the `do`.. – user2864740 Sep 26 '15 at 05:14
  • First off, I am not angry. Secondly, I downvoted precisely because the *provided example* disagrees with this answer. If a counter example (or correction) to the code is provided to show the case (and that a *property* is created), I will reverse the downvote as shown it would be shown to be incorrect. Answers that "work" but do not correctly address the issue are still wrong; this answer is not the only one I have downvoted even though it "works". – user2864740 Sep 26 '15 at 05:19
  • I have not 'lashed out'. There is no point to make this personal. I've taken time to provide a counter example. As long as it stands I cannot accept such an answer as valid, "works" or not. – user2864740 Sep 26 '15 at 05:23