How to add a character at a particular index in string in Swift

I have a string like this in Swift:

var stringts:String = "3022513240"

If I want to change it to string to something like this: "(302)-251-3240", I want to add the partheses at index 0, how do I do it?

In Objective-C, it is done this way:

 NSMutableString *stringts = "3022513240";
 [stringts insertString:@"(" atIndex:0];

How to do it in Swift?


Swift 3

Use the native Swift approach:

var welcome = "hello"

welcome.insert("!", at: welcome.endIndex) // prints hello!
welcome.insert("!", at: welcome.startIndex) // prints !hello
welcome.insert("!", at: welcome.index(before: welcome.endIndex)) // prints hell!o
welcome.insert("!", at: welcome.index(after: welcome.startIndex)) // prints h!ello
welcome.insert("!", at: welcome.index(welcome.startIndex, offsetBy: 3)) // prints hel!lo

If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.


If you are declaring it as NSMutableString then it is possible and you can do it this way:

let str: NSMutableString = "3022513240)"
str.insert("(", at: 0)
print(str)

The output is :

(3022513240)

EDIT:

If you want to add at starting:

var str = "3022513240)"
str.insert("(", at: str.startIndex)

If you want to add character at last index:

str.insert("(", at: str.endIndex)

And if you want to add at specific index:

str.insert("(", at: str.index(str.startIndex, offsetBy: 2))

var myString = "hell"
let index = 4
let character = "o" as Character

myString.insert(
    character, at:
    myString.index(myString.startIndex, offsetBy: index)
)

print(myString) // "hello"

Careful: make sure that index is smaller than or equal to the size of the string, otherwise you'll get a crash.


Maybe this extension for Swift 4 will help:

extension String {
  mutating func insert(string:String,ind:Int) {
    self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) )
  }
}