我有一些代码(我认为)可以从文件类型中分割文件名。例如," filename.txt" - > [" filename," txt"]。
但是,我没有意识到当我使用对话框打开文件名时,我得到了完整的路径(菜鸟错误,我知道)。例如,这就是我的函数返回的内容:
filename_array: ["/home/user/Downloads/filename", "txt"]
如何删除路径内容并仅返回filename
部分?
答案 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