【问题标题】:How to check if Swift URL is directory如何检查 Swift URL 是否是目录
【发布时间】:2020-12-04 23:08:07
【问题描述】:

如何检查 Swift URL 是代表文件还是目录?

URL 对象上有一个hasDirectoryPath 属性,但它背后似乎没有任何“智能”。 它只是反映了传递给 URL 的 isDirectory 值。

代码:

  let URL1 = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
  print(URL1.hasDirectoryPath)
  let URL2 = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
  print(URL2.hasDirectoryPath)

输出:

  false
  true

【问题讨论】:

标签: ios swift macos


【解决方案1】:

名称说明了一切“hasDirectoryPath”。它没有说明 URL 是一个目录并且它存在。它说它有一个目录路径。要确保 URL 是一个目录,您可以获取 URL ResourceKey isDirectoryKey:

extension URL {
    var isDirectory: Bool {
       (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
    }
}

【讨论】:

  • hasDirectoryPath 到底是什么意思呢? Swift 文档上的解释说:A Boolean that is true if the URL path represents a directory. 我解释为:路径是一个目录。
  • 哦,等等,我想我明白了,“hasDirectoryPath”可能是为了显示文件系统上的路径和 http url 之间的区别?
  • 为了让它工作,我必须在“try”调用前添加return。我正在使用 swift 5.5。
  • 这没有任何意义,除非您在返回的单行上方添加了一些代码
【解决方案2】:

其检查目录并返回真假

extension URL    {
    func checkFileExist() -> Bool {
        let path = self.path
        if (FileManager.default.fileExists(atPath: path))   {
            print("URL AVAILABLE")
            return true
        }else        {
            print("URL NOT AVAILABLE")
            return false;
        }
    }
}

用途:

if fileName.checkFileExist{
  // Here, do something
} 

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2019-10-28
    • 2011-10-10
    • 2014-10-23
    • 2012-09-12
    • 2012-03-25
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多