Create folder in Swift

I'm new to swift and I'm not sure how to create a new folder from a string path (or from some object File/ NSFile

)

This is on OS X with Cocoa.

+3


source to share


3 answers


I understand that you are trying to create a directory programmatically using swift. The code below does the same.



    var err: NSErrorPointer = nil
    let manager = NSFileManager.defaultManager()
    manager.createDirectoryAtPath("/Users/abc/Desktop/swiftDir", withIntermediateDirectories: true, attributes: nil, error: err)

      

+8


source


Xcode 8 β€’ Swift 3

extension FileManager.SearchPathDirectory {
    func createSubFolder(named: String, withIntermediateDirectories: Bool = false) -> Bool {
        guard let url = FileManager.default.urls(for: self, in: .userDomainMask).first else { return false }
        do {
            try FileManager.default.createDirectory(at: url.appendingPathComponent(named), withIntermediateDirectories: withIntermediateDirectories, attributes: nil)
            return true
        } catch {
            print(error)
            return false
        }
    }
}

      


Using:



if FileManager.SearchPathDirectory.desktopDirectory.createSubFolder(named: "untitled folder") {
    print("folder successfully created")
}

      


SearchPathDirectory

+5


source


In Swift 2.0, you have to use the new style for error handling:

let path: String = "/Users/abc/Desktop/swiftDir"
let fileManager = NSFileManager.defaultManager()
do
{
    try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
    print("Error while creating a folder.")
}

      

+3


source







All Articles