format a phone number in swift

To format a phone number in Swift, we can create an extension for UITextField that will handle the formatting. Here is an example of how we can format a US phone number (10 digits) with dashes:

main.swift
extension UITextField {
    func formatPhoneNumber() {
        // Remove any existing formatting
        var phoneNumberWithoutFormatting = self.text?.filter({ $0.isNumber })
        
        // Make sure the phone number is 10 digits
        if phoneNumberWithoutFormatting?.count == 10 {
            let firstThree = phoneNumberWithoutFormatting?.prefix(3)
            let nextThree = phoneNumberWithoutFormatting?.prefix(6).suffix(3)
            let lastFour = phoneNumberWithoutFormatting?.suffix(4)
            
            self.text = "\(firstThree!)-\(nextThree!)-\(lastFour!)"
        } else {
            // Don't format the phone number if it's not 10 digits
            self.text = phoneNumberWithoutFormatting
        }
    }
}
740 chars
19 lines

To use this extension, you can simply call textField.formatPhoneNumber() on any UITextField that you want to format the phone number for.

gistlibby LogSnag