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
}
}