Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT: Get path only

I'm searching for a predefined function for getting the path from a path including filename. So instead of getting the filename I want the other part.

Of course I can do it like my own like:

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

when extend String, but why reinvent the wheel? :-) Any idea?

like image 923
Peter71 Avatar asked Jan 11 '16 07:01

Peter71


1 Answers

The NSString method stringByDeletingLastPathComponent and the NSURL method URLByDeletingLastPathComponent do exactly what you want.

Example:

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

Update for Swift 3:

let url = URL(fileURLWithPath: "/foo/bar/file.text")
let dirUrl = url.deletingLastPathComponent()
print(dirUrl.path)
// Output: /foo/bar
like image 97
Martin R Avatar answered Nov 16 '22 03:11

Martin R