首页 > 解决方案 > 检查文件夹何时存在或不存在的可选语句

问题描述

此行获取目录名称

 let directory = NSURL(fileURLWithPath: image).deletingPathExtension?.lastPathComponent  // 

现在我有兴趣检查整个路径是否存在。但是,如果我尝试这行代码:

     if let imageDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(directory!, isDirectory: true)

我收到错误消息“条件绑定的初始化程序必须具有可选类型,而不是 URL”

我也试过directory?了。

谢谢你。

标签: iosswiftoptional

解决方案


如果您使用构造,您会得到错误原因

如果让某事= ...

您必须尝试解开可选属性。但是在您的示例中,您没有打开任何东西,因为您的财产是

第一的!

我的解决方案

if let directory = NSURL(fileURLWithPath: image).deletingPathExtension?.lastPathComponent,
   let imageDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(directory, isDirectory: true) {

}

编辑1:

使用 URL 代替 NSURL:

let directory = URL(fileURLWithPath: image).deletingPathExtension().lastPathComponent
if let imageDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(directory, isDirectory: true) {}

推荐阅读