Search code examples
swiftstringmacosprefix

Swift - String removal code not performing as expected


I'm working on a macOS Swift-app where I need to perform folder/file traversal. In this specific instance, I need to remove the first part of a file path...i.e., if a file has the path of MyFolder/MyItem, I need it to just read as MyItem for display purposes.

Based off the responses in this answer, I wrote the following code:

if fileString.hasPrefix("/") {
    fileString.remove(at: fileString.startIndex)
    print(fileString)
}

...where I remove any part of the fileString before and including "/".

However, this doesn't seem to work in practice....MyFile/MyItem doesn't get changed to MyItem, it remains as MyFile/MyItem.


Solution

  • You can locate the first (or last) slash character and remove everything from the beginning of the string up to and including that separator, for example:

    var fileString = "My Volume/My Folder/My Item"
    if let r = fileString.range(of: "/", options: .backwards) {
        fileString.removeSubrange(..<r.upperBound)
    }
    print(fileString) // My Item
    

    But if your intention is to extract the file name (last path component) for display then there is a dedicated method for that purpose:

    let fileString = "My Volume/My Folder/My Item"
    let displayName = FileManager.default.displayName(atPath: fileString)
    print(displayName) // My Item
    

    Another method is

    let fileString = "My Volume/My Folder/My Item"
    let baseName = URL(fileURLWithPath: fileString).lastPathComponent
    print(baseName) // My Item
    

    which is similar to the previous one, but does not localize the file name.