Search code examples
swiftcocoaerror-handlingswift2nsfilemanager

Create a folder with Swift


I'm trying to use NSFileManager's method createDirectoryAtPath:withIntermediateDirectories:attributes:error: in Swift.

The problem is that I have no idea what this function throws in case of error. Is this documented anywhere? If yes, where?


Solution

  • When the Swift docs says a function throws, they mean that it throws an NSError.

    Consider the following do-try-catch flow:

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    
    do {
        try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: false, attributes: nil)
    } catch {
        print(error)
        print(error.dynamicType)
    }
    

    createDirectoryAtPath will fail because the documents directory already exists. Logging the dynamicType of the error shows that it is in fact an NSError object:

    Error Domain=NSCocoaErrorDomain Code=516 "The file “Documents” couldn’t be saved in the folder “35B0B3BF-D502-4BA0-A991-D07568AB87C6” because a file with the same name already exists." UserInfo={NSFilePath=/Users/jal/Library/Developer/CoreSimulator/Devices/E8A35774-C9B7-42F0-93F1-8103FBBC7118/data/Containers/Data/Application/35B0B3BF-D502-4BA0-A991-D07568AB87C6/Documents, NSUnderlyingError=0x7fa88bd14410 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
    
    NSError