Justin Conroy Justin Conroy - 2 months ago 10
Swift Question

How can I insert characters into a String in a specific format?

I have a generic string property in the following format: 15555555555. I am trying to display it in the following format in a

UILabel
:


(555)
555-5555


I would like to avoid changing the
UILabel
size or anything to get the text to wrap because it displays different text based on a mode. I have tried using
NSMutableString
and
myString.components(separatedBy:)
among other things but am having trouble getting the code to work:

1st attempted method:

let phoneNumber = NSMutableString(string: self.phoneNumber)
phoneNumber.remove(at: 0)
phoneNumber.insert("-", at: 6)
phoneNumber.insert(")", at: 3)
phoneNumber.insert("(", at: 0)
let finalString: String = phoneNumberArray.joined()


2nd attempted method:

var phoneNumberArray = self.phoneNumber.components(separatedBy: “”)
phoneNumber.remove(at: 0)
phoneNumber.insert("-", at: 6)
phoneNumber.insert(")", at: 3)
phoneNumber.insert("(", at: 0)
let finalString: String = phoneNumberArray.joined()


Everything I’m trying is is giving an error and I’m not sure how to make it wrap in the middle other than splitting into two strings. Any help would be greatly appreciated. Thanks in advance.

Answer

Pay careful attention to the array type as you are looking for [String], not [Character].

I typed out an example using your code below. This takes the phone number and makes each digit a String element in an array. That way, you can insert and remove String characters. Also, you can actually just use a Line Feed \n in a String. This escape sequence means new line, so everything after it will “wrap”:

var phoneNumberArray : [String] = self.phoneNumber.characters.map{String($0)}
phoneNumberArray.remove(at:0)
phoneNumberArray.insert("-", at: 6)
phoneNumberArray.insert("\n", at: 3)
phoneNumberArray.insert(")", at: 3)
phoneNumberArray.insert("(", at: 0)
let finalString: String = phoneNumberArray.joined()

This code is not tested but should work.