什么是Swift 3等效的NSURL.URLByAppendingPathComponent()?

Pek*_*ica 27 xcode nsurl swift swift3

我下面的一个基本的教程在斯威夫特构建一个简单的iOS应用.

它是用Swift 2.x编写的,我使用的是XCode 8 Beta和Swift 3.

本教程建议使用NSFileManager查找数据目录.类名已更改,因此自动修复的Swift 3如下所示:

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

但是,Xcode现在抱怨说

Value of type 'URL' has no member 'URLByAddingPathComponent'
Run Code Online (Sandbox Code Playgroud)

我无法找出现在调用的方法.

NSURL类引用不包含任何提示如何从斯威夫特3解决这一问题

  • 什么是新方法名称?

  • 我在哪里可以找到Swift 3的完整类引用(或者,类的Swift 3接口URL定义了类 - 我仍然不完全理解命名法)所以我可以在将来自己研究这些?

Ham*_*ish 42

从Xcode 8 beta 4开始,它被命名appendingPathComponent(_:),并且不会抛出.

static let archiveURL = documentsDirectory.appendingPathComponent("meals")
Run Code Online (Sandbox Code Playgroud)

另外,正如Leo Dabus在评论中指出的那样,您的documentsDirectory房产将需要更改为urls(for:in:)在测试版4中使用:

static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
Run Code Online (Sandbox Code Playgroud)

(请注意,我lowerCamelCase根据Swift API设计指南制作了您的属性名称.我还建议您使用FileManager.default,而不是创建新实例.)

您可以查看Apple最新的API参考指南,了解Swift 3中发生的API命名更改.


Khu*_*pan 12

它现在已经改为appendingPathComponent(_:)并抛出,所以你需要将它包装在do-catch块中

do {
  let archiveURL = try documentsDirectory?.appendingPathComponent("meals")
} catch {
  print(error)
}
Run Code Online (Sandbox Code Playgroud)

更新

根据Xcode 8 beta 4,appendingpathcomponent(_:)不抛出错误.

有关相关信息,请参阅@Hamish的回答