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

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


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.


It has now changed to appendingPathComponent(_:) and it throws, so you need to wrap it in do - catch block

do {  let archiveURL = try documentsDirectory?.appendingPathComponent("meals")} catch {  print(error)}

Update

As per Xcode 8 beta 4, the appendingpathcomponent(_:) do not throw error.

For relevant info see answer by @Hamish


func appendingPathComponent(String)

=> Returns a new URL made by appending a path component to the original URL.

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

If it is directory:

func appendingPathComponent(String, isDirectory: Bool)

=> Returns a new URL made by appending a path component to the original URL, along with a trailing slash if the component is designated a directory.

static let archiveURL = documentsDirectory?.appendingPathComponent("meals", isDirectory: true)