Suragch Suragch - 1 year ago 34
Swift Question

'stringByAppendingPathComponent' is unavailable

I'm getting the error

'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead.

when I try to do

let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite")

This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5.

This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to
. But if I do convert it to an

let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString)

then I get the error

'NSString' is not implicitly convertible to 'String'...

and it gives me the option to "fix-it" by inserting
as String
, which brings us back to the original error.

This also happens for

What do I do?

Answer Source

You can create a URL rather rather than a String path.

let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent("test.sqlite")

If you absolutely need the path, then you can get it like this:

let path = fileURL.path!

There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths.


The following code gets the path string by a similar method but uses more error checking.

let filename = "db.sqlite"

guard let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first else {
    print("directory is nil")
guard let path = directoryURL.URLByAppendingPathComponent(filename).path else {
    print("path is nil")

print(path) // path will exist at this point

See also: