Breaking change to get file name without extension in Swift2

In Swift1, we can get the short file name without the extension using the following code:

self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension 

While I was upgrading to Swift 2, this API is no longer available. With a warning message I should use NSURL. So the new code will be:

 var filename = NSURL(fileURLWithPath: str).lastPathComponent filename = NSURL(fileURLWithPath: filename!).URLByDeletingPathExtension?.relativePath 

This is too complex a change to the API. Is there a better way to make this easier?

+7
ios filenames swift2
source share
3 answers

Why not:

 self.name = NSURL(fileURLWithPath: str).URLByDeletingPathExtension?.lastPathComponent 

I'm not sure about Swift, so there might be missing ones ! or ? .

+18
source share

This work on Swift 2.2 :

 let nameOnly = (fileName as NSString).stringByDeletingPathExtension let fileExt = (fileName as NSString).pathExtension 
+4
source share

Swift 4

 let url = URL(string: "https://example.com/myFile.html") if let fileName = url?.deletingPathExtension().lastPathComponent { // fileName: myFile self.name = fileName } 
+1
source share

All Articles