2016-05-14 62 views
9

如果喜欢获得类似于Bash的-dif条件的功能。检查路径是否是Swift2中的目录?

我知道如何测试一个文件是否存在fileExistsAtPath(),如果文件存在,它会返回一个bool“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 

这是可能的,如果是,应该如何它是执行ED?

+3

http://stackoverflow.com/a/24696209/1187415 –

+0

我同意,道歉。我把这个标记为重复。 – perhapsmaybeharry

回答

18

您可以使用告诉你path表示目录的fileExistsAtPath过载:

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

究竟是我们在Swift中使用的解决方案。真的没有一个快速的方法? –

+0

@ R.P.Carson我更新了Swift新版本的答案。 – dasblinkenlight