Bronze Challenge Solution using NSCharacterSet

The Bronze Challenge specifies using NSCharacter set to filter out alphabetic characters. I also found that it was possible to enter punctuation and symbols, so I filtered those out too. This was done in Swift 4 using Xcode 9.

A good way to test this in the iPhone Simulator is to change the ‘Keyboard Type’ for the UITextField to ‘default’ so that you can try to enter letters, punctuation or symbols.

   func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {
    let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
    let replacementTextHasDecimalSeparator = string.range(of: ".")
    
    let replacementTextHasAlphabeticCharacter = string.rangeOfCharacter(from: NSCharacterSet.letters)
    let replacementTextHasPunctuation = string.rangeOfCharacter(from: NSCharacterSet.punctuationCharacters)
    let replacementTextHasSymbols = string.rangeOfCharacter(from: NSCharacterSet.symbols)

    if existingTextHasDecimalSeparator != nil,
        replacementTextHasDecimalSeparator != nil {
        return false
    } else if replacementTextHasAlphabeticCharacter != nil {
        return false
    } else if replacementTextHasPunctuation != nil {
        return false
    } else if replacementTextHasSymbols != nil {
        return false
    } else {
        return true
    }
}

Thanks for your contribution @slgraff. Just wanted to add a small change:

Since you eliminated the use of punctuation with the line

 } else if replacementTextHasPunctuation != nil {
        return false

the code will essentially prevent you from using the ‘dot’ separator. For instance, you cannot convert anything with a decimal point, such as 13.5, because the code now prevented the use of the decimal point.

Instead, my corresponding line looks like this:

}  else if replacementTextHasPunctuation != nil , replacementTextHasDecimalSeparator == nil {

return false

I hope I haven’t misunderstood your code.