Last Updated: February 25, 2016
· anthonylevings
Speechrocket4 square

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.

Say Thanks
Awesome Job

D8c7bb04 bfe7 11e7 9a4a 7b76a32c6bdb
Full Stack Developer
Amsterdam, the Netherlands
Full Time