Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert character into string in Swift 2.0?

Tags:

swift2

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
}
like image 408
tomtclai Avatar asked Sep 24 '15 22:09

tomtclai


1 Answers

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
like image 116
Serneum Avatar answered Sep 28 '22 18:09

Serneum