-
Notifications
You must be signed in to change notification settings - Fork 208
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to get relative path? #31
Labels
Comments
relative path from what? there is no cocoa functions I think so we must implement it I could provide a non tested code
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
And I use it like that
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.
Feel free to import it into FileKit. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's have a easy method to get relative path?
The text was updated successfully, but these errors were encountered: