What's the difference between URL.standardized and URL.absoluteURL?

If url is an absolute URL, url.absoluteURL == url.

If url is a relative URL and has a non-nil baseURL, then url.absoluteURL returns an absolute URL by resolving the relativity of url in the context of baseURL (and thus url.absoluteURL != url).

If url is a relative URL, url.standardized does not return an absolute URL, and may in fact return a URL that does not resolve the same way as url (!) because url.standardized removes any leading .. components of the path.

Example:

let base = URL(string: "https://stackoverflow.com/q/43258046/77567")!
// output: "https://stackoverflow.com/q/43258046/77567"

let rel = URL(string: "../16176911", relativeTo: base)!
// output: "../../16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.absoluteURL
// output: "https://stackoverflow.com/q/16176911"

rel.standardized
// output: "16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.standardized.absoluteURL
// output: "https://stackoverflow.com/q/43258046/16176911"

I think the key difference is that two URLs with different absolute paths may actually refer to the same resource, and in that case, they would have the same standardized URL. Examples of path elements that could cause this are:

~ vs /absolute/path/to/user/home/directory
paths that include soft links
/path/to/thing vs /path/to/other/../thing
etc.

The standardized url (URL.standardizedFileURL in swift) is very useful because two URLs that point to the same file should have the same standardizedFileURL even if they have different absolute paths. So one should generally use the standardized path if they wish to compare two file URLs.

Tags:

Url

Swift