Ivan R Ivan R - 1 year ago 236
Swift Question

How to find NSDocumentDirectory in swift?

I'm trying to get path to Documents folder with code:

var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)

but xcode gives error: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'

I'm trying to understand what is wrong in code?


I have write func that return path to db in swift

func pathToFile()->String{

let filemanager = NSFileManager.defaultManager()

let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let destinationPath:NSString = documentsPath.stringByAppendingString("/items.db")

if(!filemanager.fileExistsAtPath(destinationPath) ){

let fileForCopy = NSBundle.mainBundle().pathForResource("items",ofType:"db")
filemanager.copyItemAtPath(fileForCopy,toPath:destinationPath, error: nil)

return destinationPath
return destinationPath

UPDATE 2015:
use this script for swift 2.0 http://stackoverflow.com/a/33033147/3710213

Answer Source

Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.

But as to the reasons:

First, you are confusing the argument names and types. Take a look at the function definition:

func NSSearchPathForDirectoriesInDomains(
    directory: NSSearchPathDirectory,
    domainMask: NSSearchPathDomainMask,
    expandTilde: Bool) -> AnyObject[]!
  • directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.
  • Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
  • And finally, it returns an array, not just a single path.

So that leaves us with (updated for Swift 2.0):

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download