ios - 检查文件夹何时存在或不存在的可选语句
问题描述
此行获取目录名称
let directory = NSURL(fileURLWithPath: image).deletingPathExtension?.lastPathComponent //
现在我有兴趣检查整个路径是否存在。但是,如果我尝试这行代码:
if let imageDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(directory!, isDirectory: true)
我收到错误消息“条件绑定的初始化程序必须具有可选类型,而不是 URL”
我也试过directory?
了。
谢谢你。
解决方案
如果您使用构造,您会得到错误原因
如果让某事= ...
您必须尝试解开可选属性。但是在您的示例中,您没有打开任何东西,因为您的财产是
第一的!
我的解决方案
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) {}
推荐阅读
- java - 创建类的对象时,“this”指的是哪里?
- xml - 获取 XML 文件中字符串的 XPath
- scala - Scala 中有没有办法将 Seq[(String, String)] 转换为 Seq[String]?
- javascript - 转换对象以使用扩展运算符?
- pandas - 如何用纯 PySpark 函数替换 Timedelta Pandas 函数?
- c# - 通过序列化 DataContract 将对象字段分成两个文件
- php - 将 apache2 从 php5.6 升级到 php7.3 会导致 mod_ssl 出现分段错误
- javascript - 如何减少 Phaser 中的 addEvent 延迟?
- java - SetCellValue 不适用于第一行 java
- internet-explorer - IE11中的页面加载为空