SWIFT:仅获取路径

Pet*_*r71 10 directory path swift

我正在寻找一个预定义的函数来从包含文件名的路径获取路径.因此,我没有获取文件名,而是想要另一部分.

当然,我可以像我自己一样做:

func PathOnly() -> String {
    let n = NSURL(fileURLWithPath: self).lastPathComponent?.characters.count
    return self.Left(self.characters.count - n!)
}
Run Code Online (Sandbox Code Playgroud)

当扩展String时,为什么重新发明轮子?:-) 任何的想法?

Mar*_*n R 25

NSString方法stringByDeletingLastPathComponentNSURL方法 URLByDeletingLastPathComponent做你想要什么.

例:

let path = "/foo/bar/file.text"
let dir = (path as NSString).stringByDeletingLastPathComponent
print(dir)
// Output: /foo/bar


let url = NSURL(fileURLWithPath: "/foo/bar/file.text")
let dirUrl = url.URLByDeletingLastPathComponent!
print(dirUrl.path!)
// Output: /foo/bar
Run Code Online (Sandbox Code Playgroud)

Swift 3更新:

let url = URL(fileURLWithPath: "/foo/bar/file.text")
let dirUrl = url.deletingLastPathComponent()
print(dirUrl.path)
// Output: /foo/bar
Run Code Online (Sandbox Code Playgroud)