在Swift2中断开更改以获取没有扩展名的文件名

How*_*ard 7 filenames ios swift2

在Swift1中,我们可以通过以下代码获得没有扩展名的文件短名称:

self.name = pathFilename.lastPathComponent.stringByDeletingPathExtension
Run Code Online (Sandbox Code Playgroud)

当我更新到Swift 2时,此API不再可用.有了警告信息,我必须使用NSURL.所以新代码将是:

var filename = NSURL(fileURLWithPath: str).lastPathComponent
filename = NSURL(fileURLWithPath: filename!).URLByDeletingPathExtension?.relativePath
Run Code Online (Sandbox Code Playgroud)

这是太复杂的API破坏性变化.有没有更好的方法可以使它更简单?

rma*_*ddy 18

为什么不:

self.name = NSURL(fileURLWithPath: str).URLByDeletingPathExtension?.lastPathComponent
Run Code Online (Sandbox Code Playgroud)

我不熟悉Swift,因此可能会有一些缺失!?需要.


小智 6

斯威夫特 4

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


Ale*_*ano 5

这项工作在Swift 2.2 上

let nameOnly = (fileName as NSString).stringByDeletingPathExtension
let fileExt  = (fileName as NSString).pathExtension
Run Code Online (Sandbox Code Playgroud)