Here's an alternative way to reduce a phone number to valid components using a Scanner
…
let number = "+123 456-7890"
let scanner = Scanner(string: number)
let validCharacters = CharacterSet.decimalDigits
let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#"))
var digits: NSString?
var validNumber = ""
while !scanner.isAtEnd {
if scanner.scanLocation == 0 {
scanner.scanCharacters(from: startCharacters, into: &digits)
} else {
scanner.scanCharacters(from: validCharacters, into: &digits)
}
scanner.scanUpToCharacters(from: validCharacters, into: nil)
if let digits = digits as? String {
validNumber.append(digits)
}
}
print(validNumber)
// +1234567890