I'm trying to understand how to use the function fileExistsAtPath:isDirectory:
with Swift but I get completely lost.
This is my code example:
var b:CMutablePointer<ObjCBool>? if (fileManager.fileExistsAtPath(fullPath, isDirectory:b! )){ // how can I use the "b" variable?! fileManager.createDirectoryAtURL(dirURL, withIntermediateDirectories: false, attributes: nil, error: nil) }
I can't understand how can I access the value for the b
MutablePointer. What If I want to know if it set to YES
or NO
?
The second parameter has the type UnsafeMutablePointer<ObjCBool>
, which means that you have to pass the address of an ObjCBool
variable. Example:
var isDir : ObjCBool = false if fileManager.fileExistsAtPath(fullPath, isDirectory:&isDir) { if isDir { // file exists and is a directory } else { // file exists and is not a directory } } else { // file does not exist }
Update for Swift 3 and Swift 4:
let fileManager = FileManager.default var isDir : ObjCBool = false if fileManager.fileExists(atPath: fullPath, isDirectory:&isDir) { if isDir.boolValue { // file exists and is a directory } else { // file exists and is not a directory } } else { // file does not exist }
Tried to improve the other answer to make it easier to use.
enum Filestatus { case isFile case isDir case isNot } extension URL { var filestatus: Filestatus { get { let filestatus: Filestatus var isDir: ObjCBool = false if FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir) { if isDir.boolValue { // file exists and is a directory filestatus = .isDir } else { // file exists and is not a directory filestatus = .isFile } } else { // file does not exist filestatus = .isNot } return filestatus } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With