在 Swift2 中获取不带扩展名的文件名的重大更改

Breaking change to get filename without extension in Swift2

在Swift1中,我们可以通过以下代码获取不带扩展名的文件简称:

self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension

虽然我更新到 Swift 2,但此 API 不再可用。有了警告消息,我必须使用 NSURL。所以新代码将是:

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

它太复杂了 API 中断更改。有没有更好的方法可以让它更简单?

为什么不呢:

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

我对 Swift 不是很流利,因此其中可能缺少一些 !?

这项工作在 Swift 5.5:

let nameOnly = (fileName as NSString).deletingPathExtension
let fileExt  = (fileName as NSString).pathExtension

Swift 4

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