Bronze Challenge without using NSCharacterSet

Hello everyone, I wanted to share a solution I came up with that does not use NSCharacterSet. The idea is to convert the replacement string into an Int. If if is possible to convert the string, this optional value will return an int, otherwise it will return nil.

Inside the else statement, we can check for the three valid forms of input: and int, a decimal, or nothing (for when the user presses backspace).

Thanks for reading!

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range:NSRange,
               replacementString string: String) -> Bool {

	let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
	let replacementTextHasDecimalSeparator = string.range(of: ".")
	
	// convert the replacement string into an Int, if possible
	var convertReplacementStringToInt: Int?
	convertReplacementStringToInt = Int(string)
	
	// do not allow screen update
	if existingTextHasDecimalSeparator != nil,
		replacementTextHasDecimalSeparator != nil {
			return false
	}
		
	else {
		// allow screen update if an integere is entered, a decimal is entered, or a character is deleted
		if convertReplacementStringToInt != nil || string == "." || string == "" {
			return true
		}
		
		// do not allow screen update
		else {
			return false
		}
	}
}
1 Like