Kwnstantinos Natsios Kwnstantinos Natsios - 2 months ago 8
Swift Question

Put a string before a certain string inside a text in Swift 3

I'm dealing with an issue here, I have a URL of an image which is like this

http://example.com/image/test.jpg


Which is a string.

And I would like to insert before
.jpg
a certain text like
-40x40


Is there any way to analyze the URL string and somehow to add this text so the final string should be

http://example.com/image/text-40x40.jpg


What i've tried till now is this

var finalImage = "http://example.com/image/test.jpg"
finalImage.insert("-40x40" as Character, at: finalImage.endIndex - 4)


but i get 2 errors.

1) i cant add more than 1 character and 2) i cant do the math ad endIndex.

But i can't add more than one character there.

Thanks a lot!

Answer

Try this. It uses NSURL, which exists so that path manipulations are easy and legal! The documentation is really quite good.

let s1 = "http://example.com/image/test.jpg"
let u = URL(fileURLWithPath: s1)
let exExt = u.deletingPathExtension()
let s2 = exExt.absoluteString + "-40x40.jpg"