2

I'm trying to insert a specific character in a specific index in a string lets say

var text = "1234567890"

i want that variable to add the country code of the phone number:

text = text.replacingCharacters(in: text.startIndex..<text.index(after: text.startIndex), with: "+593\\U00a0")

Then i have to format that string into something like this: "+593 23-456-7890", so i have to insert "-" into the index 8 and 11 but i have only found answers with swift 2.0. Strings had a method called insert that doesn't exists anymore. i've tried this:

text = text.insert("-", at: text.index(text.startIndex, offsetBy: +8))

but I have the following error "Cannot assign value of type '()' to type 'String'

1
  • If my answer was helpful, I would appreciate it if you accept my answer. This will mark this question as "answered" and it will give you, as well as me, some reputation. Commented Jul 20, 2017 at 15:13

1 Answer 1

10

Insert operates on the actual string itself. Therefore, there is no need to assign back to it. You can just use the following:

text.insert("-", at: text.index(text.startIndex, offsetBy: +8))

More information about inserting into a string can be found in the Swift documentation from Apple.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.