我有兩個目錄如下:查找目錄中是否包含一個URL,下面的符號鏈接
- 目錄一個包含文件X。
- 目錄乙包含一個別名目錄一個命名Ç。
因此,有文件X兩種可能的絕對網址:/A/X
和/B/C/X
。 (一個和乙可以在我的文件系統中的任何地方。)
我需要做的是,給定的文件的URL目錄乙(file:///B/
)與文件的URL文件X,確定什麼是否文件X位於目錄B內。
這就是我想出了:
extension URL {
func isIdenticalFile(to other: URL) -> Bool {
return resolvingSymlinksInPath() == other.resolvingSymlinksInPath()
}
func contains(_ other: URL) -> Bool {
guard isFileURL, other.isFileURL, let enumerator = FileManager.default.enumerator(atPath: path) else {
return false
}
for subURL in enumerator.map({ appendingPathComponent($0 as! String) }) {
if subURL.isIdenticalFile(to: other) || subURL.contains(other) {
return true
}
}
return false
}
}
let b = URL(string: "file:///B/")!
let ax = URL(string: "file:///A/X")!
let bcx = URL(string: "file:///B/C/X")!
// Both b.contains(ax) and b.contains(bcx) are true
有沒有更簡單/更有效的方式來做到這一點?
[最終解決方案,以供參考(https://gist.github.com/noahcgreen/5315666f0e9a6bac300bd8f4a40dc1d4) – Noah