41 lines
1.2 KiB
Swift
41 lines
1.2 KiB
Swift
//
|
|
// String.swift
|
|
// EmployeeDirectory
|
|
//
|
|
// Created by Matt Bruce on 1/20/25.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
extension String {
|
|
/// Formats a string into a US phone number format (XXX-XXX-XXXX).
|
|
/// Non-numeric characters are removed, and formatting is applied based on the length of the string.
|
|
/// - Returns: A formatted phone number as a string.
|
|
internal func formatUSNumber() -> String {
|
|
// format the number
|
|
return format(with: "XXX-XXX-XXXX", phone: self)
|
|
}
|
|
|
|
internal func format(with mask: String, phone: String) -> String {
|
|
let numbers = filter { $0.isNumber }
|
|
var result = ""
|
|
var index = numbers.startIndex // numbers iterator
|
|
|
|
// iterate over the mask characters until the iterator of numbers ends
|
|
for ch in mask where index < numbers.endIndex {
|
|
if ch == "X" {
|
|
// mask requires a number in this place, so take the next one
|
|
result.append(numbers[index])
|
|
|
|
// move numbers iterator to the next index
|
|
index = numbers.index(after: index)
|
|
|
|
} else {
|
|
result.append(ch) // just append a mask character
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
}
|
|
|