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?
You can't use in below Swift 2.0 because
String
stopped being acollection
in Swift 2.0. but in Swift 3 / 4 is no longer necessary now thatString
is aCollection
again. Use native approach ofString
,Collection
.To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3
If you are declaring it as
NSMutableString
then it is possible and you can do it this way:The output is :
Careful: make sure that
index
is bigger than or equal to the size of the string, otherwise you'll get a crash.//+994-55-55555
Maybe this extension for Swift 4 will help: