2014-10-13 11 views

risposta

17

Alcuni potrebbero trovare questo un po 'più ordinato. Si tratta di 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. 
} 
+2

Tecnicamente questo non è il casting, ma l'inizializzazione con 'init (_ value: T)'. – Kirsteins

+0

Quando ci pensi, sei completamente corretto, lo noterai. –

62

Il problema è che isDirectory è UnsafeMutablePointer<ObjCBool> e non UnsafeMutablePointer<Bool> forniti. È possibile utilizzare il seguente codice:

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

} 

if isDir.boolValue { 

} 
+0

Questo ha fatto il trucco. Grazie! –

+7

Su Swift 3 Bool (isDir) non funziona per me. isDir.boolValue funziona bene. Grazie –

+3

Questa è la soluzione per Swift 3 –

1

È

func isDirectory(path: String) -> Bool { 
    var isDirectory: ObjCBool = false 
    NSFileManager().fileExistsAtPath(path, isDirectory: &isDirectory) 
    return Bool(isDirectory) 
} 
0

In Swift3

var isDirectory:ObjCBool = true 
var exists = FileManager.default.fileExists(atPath: cachePath, isDirectory: &isDirectory) 
+0

Salve e benvenuto su StackOveflow. Aggiungi alcune spiegazioni alla tua risposta, poiché le risposte solo in codice non sono l'ideale. – Chaithanya

0

È possibile utilizzare il seguente codice come estensione. per verificare se esiste una directory o meno 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 
    } 
} 
Problemi correlati