SwiftyRelativePath - Compute a path between two paths

Ruby has Pathname.relative_path_from()

Java has Path.relativize()

In .NET there is Uri.MakeRelativeUri()

Surprisingly neither URL nor FileManager has a function for this.

Thus I have made a repo for this:


let u1 = URL(fileURLWithPath: "/Users/Mozart/Music/Nachtmusik.mp3")!
let u2 = URL(fileURLWithPath: "/Users/Mozart/Documents")!
u1.relativePath(from: u2)  // "../Music/Nachtmusik.mp3"

Hopefully this function can be useful to some of you.

1 Like

You might want to take a look at .canonicalPathKey (NSURLCanonicalPathKey). On Apple platforms a lot of the standard UNIXy paths exist within /private/, with corresponding symlinks from the root. So /etc/ is actually /private/etc/.

$ ls -ld /etc
lrwxr-xr-x@ 1 root  wheel  11 10 Dec  2016 /etc -> private/etc
$ ls -ld /private/etc
drwxr-xr-x  131 root  wheel  4454 16 Jan 08:33 /private/etc

If you don’t canonicalise the paths you can get tripped up by this.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"

1 Like

Yes, thanks. This surprised me, a few years ago, when I made a file manager.