2

I'm currently programming an os x application with swift, but I can't figure how to loop through or even get the names of all folders at a certain path. Maybe something with fm.enumeratorAtPath?

1 Answer 1

6

I use enumeratorAtURL. Here's some code that shows an example of how to print the directories in the user's home directory.

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.
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This certainly should give the general idea. However, it does not compile in Xcode 6.1.1.
Thanks @MartinR, I fixed the compile errors and tried it in a playground. It compiles and works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.