How to split filename from file extension in Swift?

前端 未结 21 1908
陌清茗
陌清茗 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 03:57

    Try this for a simple Swift 4 solution

    extension String {
        func stripExtension(_ extensionSeperator: Character = ".") -> String {
            let selfReversed = self.reversed()
            guard let extensionPosition = selfReversed.index(of: extensionSeperator) else {  return self  }
            return String(self[..<self.index(before: (extensionPosition.base.samePosition(in: self)!))])
        }
    }
    
    print("hello.there.world".stripExtension())
    // prints "hello.there"
    
    0 讨论(0)
  • 2020-12-01 03:58

    SWIFT 3.x Shortest Native Solution

    let fileName:NSString = "the_file_name.mp3"
    let onlyName = fileName.deletingPathExtension
    let onlyExt = fileName.pathExtension
    

    No extension or any extra stuff (I've tested. based on @gabbler solution for Swift 2)

    0 讨论(0)
  • 2020-12-01 03:58

    Swift 5

     URL(string: filePath)?.pathExtension
    
    0 讨论(0)
  • 2020-12-01 03:59

    In Swift 2.1, it seems that the current way to do this is:

    let filename = fileURL.URLByDeletingPathExtension?.lastPathComponent
    let extension = fileURL.pathExtension
    
    0 讨论(0)
  • 2020-12-01 04:00

    Latest Swift 4.2 works like this:

    extension String {
        func fileName() -> String {
            return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
        }
    
        func fileExtension() -> String {
            return URL(fileURLWithPath: self).pathExtension
        }
    }
    
    0 讨论(0)
  • 2020-12-01 04:01

    Solution Swift 4

    This solution will work for all instances and does not depend on manually parsing the string.

    let path = "/Some/Random/Path/To/This.Strange.File.txt"
    
    let fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent
    
    Swift.print(fileName)
    

    The resulting output will be

    This.Strange.File
    
    0 讨论(0)
提交回复
热议问题