肇鑫的技术博客

业精于勤,荒于嬉

URL的path相等,但是URL却可能不相等的问题

与预期的不同,URL即使path相同,URL也可能是不同的。因此,应避免使用init(fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?),使用appendingPathComponent(_:isDirectory:)作为替代。

let url = URL(fileURLWithPath: "foo/bar", isDirectory: false)
let baseURL = url.deletingLastPathComponent()
let newURL = URL(fileURLWithPath: "bar", isDirectory: false, relativeTo: baseURL)
let testURL = baseURL.appendingPathComponent("bar")

print(url == newURL) // prints false
print(url.path == newURL.path) // prints true

print(url == testURL) // prints true
print(url.path == testURL.path) // prints true