This function takes in an Int like 324543
and returns a String like "$3245.43"
My attempt is below, but Swift 2 does not like atIndex: 0
How would I go about inserting characters into a string instead?
func stylizeCents (cent: Int) -> String { var styledCents = String(cent) let dollarSign : Character = "$" let dot : Character = "." let count = styledCents.characters.count styledCents.insert(dollarSign, atIndex: 0) // error styledCents.insert(dot, atIndex: count-1) // error }
This appears to have already been solved in this answer.
Swift 2.0
You can use a string extension:
extension String { func insert(string:String,ind:Int) -> String { return String(self.characters.prefix(ind)) + string + String(self.characters.suffix(self.characters.count-ind)) } }
used like:
var url = "http://www.website.com" url = url.insert("s", ind: 4) // outputs https://www.website.com
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