I have a string like this in Swift:
var stringts:String = \"3022513240\"
If I want to change it to string to something like this: \"(
To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3
func arrangeUSFormat(strPhone : String)-> String {
var strUpdated = strPhone
if strPhone.characters.count == 10 {
strUpdated.insert("(", at: strUpdated.startIndex)
strUpdated.insert(")", at: strUpdated.index(strUpdated.startIndex, offsetBy: 4))
strUpdated.insert(" ", at: strUpdated.index(strUpdated.startIndex, offsetBy: 5))
strUpdated.insert("-", at: strUpdated.index(strUpdated.startIndex, offsetBy: 9))
}
return strUpdated
}
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.
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 bigger than or equal to the size of the string, otherwise you'll get a crash.