Last Updated: February 25, 2016
·
1.545K
· anthonylevings

Swift: A one-line method to add insert functionality to String instances (Xcode 6 Beta 5)

// create an extension for String
extension String {
    // create an insert method that returns a string
    func insert(string:String,ind:Int) -> String {
        // use prefix and suffix algorithms to construct the new string
        return  prefix(self,ind) + string + suffix(self,countElements(self)-ind)
    }
}

// call the new method
"Hello World!".insert("Swift ", ind: 6)

This was first featured on my blog.