How to delete last path component of a String in Swift?

You can separate your url into two parts like so:

let str : NSString = "www.music.com/Passion/PassionAwakening.mp3" 
let path : NSString = str.stringByDeletingLastPathComponent
let ext : NSString = str.lastPathComponent

print(path)
print(ext)

Output

www.music.com/Passion
PassionAwakening.mp3

For more info please have a look at this link.


You should really do away with legacy NS Objective-C classes and manual path string splitting where possible. Use URL instead:

let url = URL(fileURLWithPath: "a/b/c.dat", isDirectory: false)
let path = url.deletingLastPathComponent().relativePath // 'a/b'
let file = url.lastPathComponent // 'c.dat'

That being said, Apple has an explicit FilePath type starting with macOS 11, but with no path manipulation methods. For those you'd have to include the external system package

If you are on macOS 12, the methods from the external package are now also available on the system.


This works for Swift 3.0 as well:

let fileName = NSString(string: "11/Passion/01PassionAwakening.mp3").lastPathComponent

Tags:

Ios

Swift