Will Richardson
Will Richardson

Reputation: 7960

Create Folder in Swift

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

This is on OS X with Cocoa.

Upvotes: 7

Views: 14327

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236260

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
        }
    }
}

Usage:

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

SearchPathDirectory

Upvotes: 6

j.s.com
j.s.com

Reputation: 1458

In Swift 2.0 you must 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.")
}

Upvotes: 4

Seema Kadavan
Seema Kadavan

Reputation: 2638

My understanding is that you are trying to create a directory programmatically using swift. The code given below does the same.

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

Upvotes: 18

Related Questions