I have a string like this in Swift:
var stringts:String = \"3022513240\"
If I want to change it to string to something like this: \"(
Swift 4.2 version of Dilmurat's answer (with code fixes)
extension String {
mutating func insert(string:String,ind:Int) {
self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) )
}
}
Notice if you will that the index must be against the string you are inserting into (self) and not the string you are providing.
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 phone= "+9945555555"
var indx = phone.index(phone.startIndex,offsetBy: 4)
phone.insert("-", at: indx)
index = phone.index(phone.startIndex, offsetBy: 7)
phone.insert("-", at: indx)
//+994-55-55555
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.
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) )
}
}
You can't use in below Swift 2.0 because String
stopped being a collection
in Swift 2.0. but in Swift 3 / 4 is no longer necessary now that String
is a Collection
again. Use native approach of String
,Collection
.
var stringts:String = "3022513240"
let indexItem = stringts.index(stringts.endIndex, offsetBy: 0)
stringts.insert("0", at: indexItem)
print(stringts) // 30225132400