Daniel Rushton
Daniel Rushton

Reputation: 578

Issue with returning a Directory Enumerator from NSFileManager using enumeratorAtUrl in Swift

I am attempting to return a NSDirectoryEnumerator object from the NSFileManager method enumeratorAtUrl. This results in a compiler error: Cannot convert the expressions type 'NSDirectoryEnumerator!' to type 'NSDirectoryEnumeratorOptions'

let url:NSURL = NSURL(fileURLWithPath: "/")
var keys:Array<AnyObject> = [NSURLNameKey, NSURLIsDirectoryKey]
var manager:NSFileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = manager.enumeratorAtURL(url,includingPropertiesForKeys: keys, options: 0, errorHandler: nil)

This works in Obj-C but not Swift.. Has anyone else encountered this issue?

Upvotes: 5

Views: 3789

Answers (3)

Marc
Marc

Reputation: 3070

Swift 3.1+

let url = URL(fileURLWithPath: "/")
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let manager = FileManager.default
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: keys, options: options, errorHandler: nil)

Swift 2.0

No options:

let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: [], errorHandler: nil)

One option:

let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: .SkipsHiddenFiles, errorHandler: nil)

Multiple options:

let options: NSDirectoryEnumerationOptions = [.SkipsHiddenFiles, .SkipsPackageDescendants]
let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: options, errorHandler: nil)

Upvotes: 5

phatblat
phatblat

Reputation: 4070

@Kendall's answer is perfect for most cases, but if you need to adjust the behavior of the enumerator, here are some examples.

Configure the enumerator to skip hidden files:

let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: .SkipsHiddenFiles, errorHandler: nil)

If you need to set multiple options, you "or" them together:

let options: NSDirectoryEnumerationOptions = .SkipsHiddenFiles | .SkipsPackageDescendants
let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: options, errorHandler: nil)

Upvotes: 1

Try this:

let enumerator:NSDirectoryEnumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: NSDirectoryEnumerationOptions(), errorHandler: nil)

Or in short, pass in NSDirectoryEnumerationOptions() instead of "0".

"0" is not really a member of the enumeration it is looking for.

Upvotes: 8

Related Questions