【问题标题】:Check if path is a directory in Swift2? [duplicate]检查路径是否是 Swift2 中的目录? [复制]
【发布时间】:2016-09-10 13:33:47
【问题描述】:

如果想获得类似于 Bash 的 -d if 条件的功能。

我知道如何使用fileExistsAtPath() 测试文件是否存在,如果文件存在则返回布尔值“true”,如果不存在则返回“false”(假设path 是包含路径的字符串到文件):

if NSFileManager.fileExistsAtPath(path) {
    print("File exists")
} else {
    print("File does not exist")
}

但是,我想检查path中指定的路径是否是目录,类似于下面的bash代码:

if [ -d "$path" ]; then
    echo "$path is a directory"
elif [ -f "$path" ]; then
    # this is effectively the same as fileExistsAtPath()
    echo "$path is a file"
fi

这是否可能,如果可以,应该如何执行?

【问题讨论】:

标签: swift directory swift2 nsfilemanager


【解决方案1】:

您可以使用fileExistsAtPath 的重载,它告诉您path 代表一个目录:

var isDir : ObjCBool = false
let path = ...
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path, isDirectory:&isDir) {
    print(isDir.boolValue ? "Directory exists" : "File exists")
} else {
    print("File does not exist")
}

【讨论】:

  • 我们必须在 Swift 中使用的解决方案到底是怎样的。真的没有快捷的方法吗?
  • @R.P.Carson 我更新了新版 Swift 的答案。
  • 4 年后我们在这里:D
猜你喜欢
  • 2022-01-02
  • 2015-06-20
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多