How to split filename from file extension in Swift?

前端 未结 21 1918
陌清茗
陌清茗 2020-12-01 03:24

Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

let soundURL = NSBundle.mainBundle().URLForReso         


        
21条回答
  •  春和景丽
    2020-12-01 04:02

    Works in Swift 5. Adding these behaviors to String class:

    extension String {
    
        func fileName() -> String {
            return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent 
        }
    
        func fileExtension() -> String {
            return URL(fileURLWithPath: self).pathExtension
        }
    }
    

    Example:

    let file = "image.png"
    let fileNameWithoutExtension = file.fileName()
    let fileExtension = file.fileExtension()
    

提交回复
热议问题