nvzqz / FileKit

Simple and expressive file management in Swift
https://nvzqz.github.io/FileKit/docs/
MIT License
2.34k stars 208 forks source link

How to get relative path? #31

Open devSC opened 8 years ago

devSC commented 8 years ago

It's have a easy method to get relative path?

phimage commented 7 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

ivankolesnik commented 7 years ago

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.

neoneye commented 6 years ago

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.