Replace extension of a filename in swift

I would totally agree with @Rob's answer (Swift 3 Section). However, since:

The Swift overlay to the Foundation framework provides the URL structure, which bridges to the NSURL class.

NSURL Documentation.

it should be achievable by using the URL structure, as follows:

let fileURL = URL(fileURLWithPath: path)
let destinationURL = fileURL.deletingPathExtension().appendingPathExtension("newextension")

So the deletingPathExtension() now is an instance method (instead of optional variable as declared in the NSURL):

If the URL has an empty path (e.g., http://www.example.com), then this function will return the URL unchanged.

which means you don't have to handle the unwrapping of if, i.e it won't crash if the path is invalid -as mentioned in its documentation-.


A literal translation in Swift 4 would be:

let path2 = String(path[..<path.range(of: ".", options: .backwards)!.lowerBound] + ".newextension")

But Apple has been transitioning us away from String paths, but instead wants us to URL for files in our local file system.

For example, let's say we had some reference to some file in our documents directory:

let fileURL = try! FileManager.default
    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)   // nowadays, you might even prefer `.applicationSupportDirectory
    .appendingPathComponent("test.png")

If you wanted to replace that .png with .jpg, you'd do:

let jpgURL = fileURL
    .deletingPathExtension()
    .appendingPathExtension("jpg")

For previous Swift versions, see previous revision of this answer.

Tags:

Ios

Swift