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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With