Reputation: 578
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
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
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
Reputation: 75077
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