Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking change to get filename without extension in Swift2

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

self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension

While I updated to Swift 2, this API is not available anymore. With the warning message, I have to use NSURL. So the new code will be:

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

It is too complex API breaking change. Is there a better way that could make it simpler?

like image 836
Howard Avatar asked Sep 27 '15 04:09

Howard


People also ask

How do you get the name of a file without the extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

How do I get filenames without an extension in Python?

Get filename from the path without extension using rsplit() Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator.

How do you remove an extension from a string in Python?

Given a file name, we can remove the file extension using the os. path. splitext() function. The splitext() function takes the file name as its input argument and returns a tuple containing the file name as its first element and the file extension as its second argument.


2 Answers

Why not:

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

I'm not fluent in Swift so there may be some missing ! or ? needed in there.

like image 192
rmaddy Avatar answered Sep 30 '22 18:09

rmaddy


Swift 4

let url = URL(string: "https://example.com/myFile.html")
if let fileName = url?.deletingPathExtension().lastPathComponent {
    // fileName: myFile
    self.name = fileName
}
like image 41
John Cromie Avatar answered Sep 30 '22 18:09

John Cromie