How can I check if a Swift URL represents a file or a directory?
There is a hasDirectoryPath
attribute on the URL object, but there doesn't seem to be any 'intelligence' behind it.
It just reflects the isDirectory
value passed to the URL.
code:
let URL1 = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
print(URL1.hasDirectoryPath)
let URL2 = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
print(URL2.hasDirectoryPath)
output:
false
true
The name says it all "hasDirectoryPath". It doesn't state that the URL is a directory and it exists. It says that it has a directory path. To make sure that the URL is a directory you can get URL ResourceKey isDirectoryKey:
extension URL {
var isDirectory: Bool {
(try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
}
}