Is it safe to use FileManager.enumerator and remove the files as they are enumerated?

Is it safe to use FileManager.enumerator and remove the files as they are enumerated, or would deleteing the enumerated file interfere with the enumerator?

Replies

No. There’s two potential gotchas here:

  • Deleting an item might upset the enumeration itself. I’m not sure whether this is a problem in practice, but it’s not something I’d want to rely on.

  • The enumerator returns directories first, and thus you can’t delete the directory because it’s not empty.

With regards the second point, consider a directory structure like this:

dir/
    file.txt

The enumerator will return

dir
before it returns
file.txt
, and thus deleting
dir
will fail because it’s not empty.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"