如何仅解析文件的实际名称而不是完整路径?

时间:2017-03-18 00:22:36

标签: swift parsing swift3

我有一些代码(我认为)可以从文件类型中分割文件名。例如," filename.txt" - > [" filename," txt"]。

但是,我没有意识到当我使用对话框打开文件名时,我得到了完整的路径(菜鸟错误,我知道)。例如,这就是我的函数返回的内容:

filename_array: ["/home/user/Downloads/filename", "txt"]

如何删除路径内容并仅返回filename部分?

1 个答案:

答案 0 :(得分:0)

Apple一直试图摆脱所有“路径为字符串”的风格并将其迁移到URL。路径操作API已从String中移除并移至URL

let path = "/home/user/Downloads/filename.txt"
let url = URL(fileURLWithPath: path)

let fileNameOnly  = url.deletingPathExtension().lastPathComponent   // filename
let fileExtention = url.pathExtension                               // txt

或者你可以使用NSString

来做旧式的学校风格
let path = "/home/user/Downloads/filename.txt"
let fileName = (path as NSString).lastPathComponent as NSString // filename.txt

let fileNameOnly = fileName.deletingPathExtension // filename
let fileExtension = fileName.pathExtension        // txt