Cocoa/Swift: 遍历路径中的文件夹名称

Cocoa/Swift: Loop through names of folder in path

我目前正在使用 swift 编写 os x 应用程序,但我不知道如何遍历甚至获取特定路径中所有文件夹的名称。也许 fm.enumeratorAtPath?

我用enumeratorAtURL。下面是一些代码,展示了如何打印用户主目录中的目录的示例。

if let dirURL = NSURL(fileURLWithPath: NSHomeDirectory()) {
    let keys = [NSURLIsDirectoryKey, NSURLLocalizedNameKey]
    let fileManager = NSFileManager.defaultManager()
    let enumerator = fileManager.enumeratorAtURL(
        dirURL,
        includingPropertiesForKeys: keys,
        options: (NSDirectoryEnumerationOptions.SkipsPackageDescendants |
            NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants |
            NSDirectoryEnumerationOptions.SkipsHiddenFiles),
        errorHandler: {(url, error) -> Bool in
            return true
        }
    )
    while let element = enumerator?.nextObject() as? NSURL {
        var getter: AnyObject?
        element.getResourceValue(&getter, forKey: NSURLIsDirectoryKey, error: nil)
        let isDirectory = getter! as Bool
        element.getResourceValue(&getter, forKey: NSURLLocalizedNameKey, error: nil)
        let itemName = getter! as String
        if isDirectory {
            println("\(itemName) is a directory in \(dirURL.absoluteString)")
            //do something with element here.
        }
    }
}