在 Swift 中创建文件夹

Create Folder in Swift

我是 swift 的新手,我不确定如何从字符串路径(或某种 File/ NSFile 对象)创建新文件夹

这是在 OS X 上 Cocoa。

我的理解是您正在尝试使用 swift 以编程方式创建目录。下面给出的代码也是如此。

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

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

用法:

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

SearchPathDirectory

在 Swift 2.0 中,您必须使用新的错误处理方式:

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.")
}