Prevent a UITextField from being input with aphabetic characters The goal is to disallow typing alphabetic characters as input in a UITextField.

Please tell me if this approach is convenient.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
        let charSet = CharacterSet.letters
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeparator = string.range(of: ".")
        let existingTextHasAlphabeticCharacters = textField.text?.rangeOfCharacter(from: charSet)
        let replacementTextHasAlphabeticCharacters = string.rangeOfCharacter(from: charSet)

        if existingTextHasDecimalSeparator != nil,
            replacementTextHasDecimalSeparator != nil {
            return false
        } else if existingTextHasAlphabeticCharacters != nil ||
                    replacementTextHasAlphabeticCharacters != nil {
                return false
        } else {
            return true
        }
    }
If you want to disallow letters as input, why do you also test the old string of the text field? And why do you test, if the old and the new string contain a dot? The very simple solution to forbid letters is to use the one liner

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
    return string.rangeOfCharacter(from: CharacterSet.letters) == nil
}


or

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
    return string.rangeOfCharacter(from: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) == nil
}


if you want to be more specific about the disallowed characters.