Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace extension of a filename in swift

Tags:

ios

swift

Given an string with format filename.fileextension I want to replace the fileextension with newextension. How can I do it?

In java it would be

foo.substring(0, foo.lastIndexOf(".")) + ".newextension"
like image 642
Addev Avatar asked Nov 27 '14 12:11

Addev


1 Answers

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-.

like image 59
Ahmad F Avatar answered Sep 19 '22 12:09

Ahmad F