Open devSC opened 8 years ago
relative path from what? from current path?
there is no cocoa functions I think so we must implement it
I could provide a non tested code
return a Path will be more elegant
extension Path {
func stringWithPathRelative(to anchorPath: Path) -> String {
let pathComponents = self. components
let anchorComponents = anchorPath. components
var componentsInCommon = 0
for (c1, c2) in zip(pathComponents, anchorComponents) {
if c1 != c2 {
break
}
componentsInCommon += 1
}
let numberOfParentComponents = anchorComponents.count - componentsInCommon
let numberOfPathComponents = pathComponents.count - componentsInCommon
var relativeComponents = [String]()
relativeComponents.reserveCapacity(numberOfParentComponents + numberOfPathComponents)
for _ in 0..<numberOfParentComponents {
relativeComponents.append("..")
}
relativeComponents.appendContentsOf(pathComponents[componentsInCommon..<pathComponents.count])
return String.pathWithComponents(relativeComponents)
}
}
I have something like this in my extension
func relativeTo(path: Path) -> Path? {
let root = path.components
let this = self.components
guard this.starts(with: root) else {
return nil
}
let rel = this.suffix(from: root.endIndex)
let path = rel.map({ $0.rawValue }).joined(separator: "/")
return Path(path)
}
And I use it like that
let filePath = file.relativeTo(path: Path.userDocuments)
This function does not handle some edge cases, but it suits my needs.
I have made separate repo, SwiftyRelativePath, for just this purpose with tests for edge cases.
let url0 = URL(fileURLWithPath: "/computer/qubit/17")
let url1 = URL(fileURLWithPath: "/computer/lab")
url0.relativePath(from: url1) // -> "../qubit/17"
Feel free to import it into FileKit.
It's have a easy method to get relative path?