Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created April 19, 2020 16:31
Show Gist options
  • Save dfrobison/0622433624f24dcc10fed36137581b43 to your computer and use it in GitHub Desktop.
Save dfrobison/0622433624f24dcc10fed36137581b43 to your computer and use it in GitHub Desktop.
[Simple phone number formatter] Phone number formatter based on a pattern
func formatPhone(phone: String) -> String {
let cleanPhoneNumber = phone.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
let mask = "(XXX) XXX-XXXX"
var result = ""
var index = cleanPhoneNumber.startIndex
for ch in mask where index < cleanPhoneNumber.endIndex {
if ch == "X" {
result.append(cleanPhoneNumber[index])
index = cleanPhoneNumber.index(after: index)
} else {
result.append(ch)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment