Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created April 20, 2017 22:23
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennanMKE/a0a2ee6aa5a2e2e66297c580c4df0d66 to your computer and use it in GitHub Desktop.
Save brennanMKE/a0a2ee6aa5a2e2e66297c580c4df0d66 to your computer and use it in GitHub Desktop.
Directory Exists at Path in Swift
fileprivate func directoryExistsAtPath(_ path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
@yarodevuci
Copy link

ObjCBool(true)
&isDirectory

Can you explain this?

@yeansang
Copy link

@yarodevuci
ObjCBool is use in ObjectC. Which mean it can match to pointer address. So isDirectory: &isDirectory mean "i just send pointer address, and fileExists will fill in isDirectory value".
If you don't understand it: It is old black magic. Just use it and naver ask about it.

@brennanMKE
Copy link
Author

@yarodevuci In Swift there are no pointers and this function requires a pointer to a boolean value. This can be done using ObjCBool instead of the usual Bool type. See Apple docs for details.

@venkat20390
Copy link

is fileExists case-insensitive? It considers "test" and "Test" as different folders. Any way to fix this?

@Luten
Copy link

Luten commented May 14, 2019

@venkat20390, fileExists must conform to the way OS file system treats folders.
If test and Test are different folders on file system - then FileManager should treat them as different folders

@TheImShrey
Copy link

TheImShrey commented Jul 14, 2021

@yarodevuci , I'm assuming this fileExists function does two things, it returns if given path is present and will update boolean using poiter to its address if the provided path is Directory to True else False.

Hence we are doing exists && isDirectory.boolValue in the end.

from documentation:
isDirectory: Upon return, contains true if path is a directory or if the final path element is a symbolic link that points to a directory; otherwise, contains false. If path doesn’t exist, this value is undefined upon return. Pass NULL if you do not need this information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment