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?
GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.
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.
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.
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.
Swift 4
let url = URL(string: "https://example.com/myFile.html")
if let fileName = url?.deletingPathExtension().lastPathComponent {
// fileName: myFile
self.name = fileName
}
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