Created
April 19, 2020 16:31
-
-
Save dfrobison/0622433624f24dcc10fed36137581b43 to your computer and use it in GitHub Desktop.
[Simple phone number formatter] Phone number formatter based on a pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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