30

The method fileExistsAtPath() in the example below accept single argument only.

if fm.fileExistsAtPath(result, isDirectory:&isDir) {

The exact error message is: "Extra argument 'isDirectory' in call".

Any idea what's wrong?

Georg Tuparev
  • 441
  • 2
  • 6
  • 11
  • Related: https://stackoverflow.com/questions/24696044/nsfilemanager-fileexistsatpathisdirectory-and-swift – Martin R Aug 19 '18 at 04:18

6 Answers6

63

The problem is that isDirectory is UnsafeMutablePointer<ObjCBool> and not UnsafeMutablePointer<Bool> you provide. You can use the following code:

var isDir = ObjCBool(false)
if NSFileManager.defaultManager().fileExistsAtPath("", isDirectory: &isDir) {

}

if isDir.boolValue {

}
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
28

Some might find this a little neater. This is Swift 3.

var directory: ObjCBool = ObjCBool(false)
var exists: Bool = FileManager.default.fileExists(atPath: "…", isDirectory: &directory)

if exists && directory.boolValue {
    // Exists. Directory.
} else if exists {
    // Exists.
}
Ian Bytchek
  • 8,804
  • 6
  • 46
  • 72
1

It is

func isDirectory(path: String) -> Bool {
  var isDirectory: ObjCBool = false
  NSFileManager().fileExistsAtPath(path, isDirectory: &isDirectory)
  return Bool(isDirectory)
}
onmyway133
  • 45,645
  • 31
  • 257
  • 263
0

In Swift3

var isDirectory:ObjCBool = true
var exists = FileManager.default.fileExists(atPath: cachePath, isDirectory: &isDirectory)
TanJunHao
  • 216
  • 2
  • 2
  • Hello, and welcome to StackOveflow. Please add some explanation to your answer, as code-only answers are not ideal. – Chait Mar 07 '17 at 03:36
0

You can use the following code as an extension . to check if a directory exists or not in Swift 4.0

import Foundation

extension FileManager {

    func directoryExists (atPath path: String) -> Bool {
        var directoryExists = ObjCBool.init(false)
        let fileExists = FileManager.default.fileExists(atPath: path, isDirectory: &directoryExists)

        return fileExists && directoryExists.boolValue
    }
}
Kumar C
  • 525
  • 6
  • 21
0

This is Swift 5.3.

var directoryExists: ObjCBool = ObjCBool(false)
        let fileExists = FileManager.default.fileExists(atPath: path, isDirectory: UnsafeMutablePointer<ObjCBool>(mutating: withUnsafePointer(to: &directoryExists){ $0 }))

It seems like not allowed to check file and directory in the same time.

EZen
  • 1
  • 1