What is the Swift 3 equivalent of NSURL.URLByAppendingPathComponent()?

Pekka picture Pekka · Aug 7, 2016 · Viewed 17.6k times · Source

I'm following a basic tutorial on building a simple iOS app in Swift.

It is written in Swift 2.x, and I work with XCode 8 Beta and Swift 3.

The tutorial suggests using NSFileManager to find a data directory. Class names have changed, so the auto-fixed Swift 3 looks like this:

static let DocumentsDirectory = FileManager().urlsForDirectory(.documentDirectory, inDomains:.userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals")

However, Xcode now complains that

Value of type 'URL' has no member 'URLByAddingPathComponent'

I am unable to find out what the method is called now.

The NSURL Class Reference doesn't contain any hints as to how to address it from Swift 3

  • What is the new method name?

  • Where do I have to go to find a complete class reference for Swift 3 (or, the Swift 3 interface to the library the URL class is defined in - I still don't completely understand the nomenclature) so I can research these myself in the future?

Answer

Hamish picture Hamish · Aug 7, 2016

As of Xcode 8 beta 4, it is named appendingPathComponent(_:), and does not throw.

static let archiveURL = documentsDirectory.appendingPathComponent("meals")

Also as Leo Dabus points out in the comments, your documentsDirectory property will need changing to use urls(for:in:) in beta 4:

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

(Note that I've made your property names lowerCamelCase, as per the Swift API design guidelines. I would also recommend using FileManager.default, rather than creating a new instance.)

You can take a look at Apple's latest API reference guide to see the API naming changes that have taken place in Swift 3.