SWIFT: get only the path

I am looking for a predefined function to get the path from the path, including the file name. So instead of getting the file name, I want another part.

Of course, I can do this as my own:

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

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

+5
source share
1 answer

The NSString method stringByDeletingLastPathComponent and the NSURL URLByDeletingLastPathComponent method 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 
+13
source

Source: https://habr.com/ru/post/1240315/


All Articles