why do you not recommend using strings but URLS?
Back in the Mac OS X 10.5 days we made a concerted effort to move Cocoa from identifying file system objects by path to identifying them by URL. At the time the impetus was the introduction of “file system reference URLs”, which provided facilities for folks moving from the traditional Mac OS File Manager (I’m talking Mac OS 9 here, not Cocoa’s NSFileManager, which is exposed to Swift as
FileManager
). Obviously that effort is irrelevant to folks working on iOS, but it turned out that the effort wasn’t wasted because other changes have piggybacked on top of it.
One key point here is that URLs can carry state beyond what’s feasible for a simple string, and that facilitates a number of cool features:
The URL resource APIs support caching. So, for example, when you call
FileManager.default.contentsOfDirectory(at:includingPropertiesForKeys:options:)
you pass in a set of resource keys you intend to look at. The resulting URLs will have those keys cached so that you can access them quickly via resourceValues(forKeys:)
. The end result is a very efficient use of the file system, where the contentsOfDirectory(…)
call results in a single bulk file system operation (getattrlistbulk
) that lists the directory and returns the requested attributes for each item. Neat-o!URLs can carry around security information, which is the mechanism underlying the OS’s ability to give you access to items outside of your container (see
startAccessingSecurityScopedResource()
and stopAccessingSecurityScopedResource()
).
A second point is that URLs make it easier to draw a line between a file system location and general text. For example, if you have a string you have to remember whether that string is a path (that is, a file system location) or a general string (which you might happen to use as a file name). OTOH, using URLs for file system locations makes that very clear [1].
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] You could argue that we should use a separate type for file system URLs and non-file system URLs, and I generally support that position. However, in the absence of such a distinction URLs are still better than paths.