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"
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 theNSURL
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-.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With