How to split filename from file extension in Swift?

前端 未结 21 1944
陌清茗
陌清茗 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:46

    Strings in Swift can definitely by tricky. If you want a pure Swift method, here's how I would do it:

    1. Use find to find the last occurrence of a "." in the reverse of the string
    2. Use advance to get the correct index of the "." in the original string
    3. Use String's subscript function that takes an IntervalType to get the strings
    4. Package this all up in a function that returns an optional tuple of the name and extension

    Something like this:

    func splitFilename(str: String) -> (name: String, ext: String)? {
        if let rDotIdx = find(reverse(str), ".") {
            let dotIdx = advance(str.endIndex, -rDotIdx)
            let fname = str[str.startIndex..

    Which would be used like:

    let str = "/Users/me/Documents/Something.something/text.txt"
    if let split = splitFilename(str) {
        println(split.name)
        println(split.ext)
    }
    

    Which outputs:

    /Users/me/Documents/Something.something/text
    txt
    

    Or, just use the already available NSString methods like pathExtension and stringByDeletingPathExtension.

提交回复
热议问题