1

There is common pattern for iOS Documents directory retrieval:

let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]

However, if paths array is empty above code will crash with 'Index out of bounds' error.

Is it safe to assume that Documents directory is always available and that paths will always contain at least one entry in above code?

I want to avoid paranoid programming and code sprinkled with unnecessary testing for Documents directory existence.

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
  • There's [this extension](http://stackoverflow.com/a/30593673/3397217) that handles arrays: you can *safely* get the array's contents at some index. You still have to check whether it is nil though :/ – LinusGeffarth Apr 19 '17 at 20:16
  • 1
    The Documents folder is always created for you. See the [File System Programming Guide](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html) to decide whether you should use Documents vs something else (e.g. Caches or something else). – Rob Apr 19 '17 at 20:38

1 Answers1

2

You could use the alternative API with the option to create the directory

let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, 
                                                       in: .userDomainMask, 
                                           appropriateFor: nil, 
                                                   create: true)
vadian
  • 274,689
  • 30
  • 353
  • 361