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:
If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.
You can't, because in Swift string indices (String.Index) is defined in terms of Unicode grapheme clusters, so that it handles all the Unicode stuff nicely. So you cannot construct a String.Index from an index directly. You can use
advance(theString.startIndex, 3)
to look at the clusters making up the string and compute the index corresponding to the third cluster, but caution, this is an O(N) operation.In your case, it's probably easier to use a string replacement operation.
Check out this blog post for more details.