NSFileManager fileExistsAtPath:isDirectory and swi

2020-01-28 04:05发布

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?

标签: swift
2条回答
ら.Afraid
2楼-- · 2020-01-28 04:27

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
}
查看更多
家丑人穷心不美
3楼-- · 2020-01-28 04:36

Tried to improve the other answer to make it easier to use.

extension URL {
    enum Filestatus {
        case isFile
        case isDir
        case isNot
    }

    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
        }
    }
}
查看更多
登录 后发表回答