Bronze Challenge - my solution

#1

It seems to restrict every possible way a user could enter a character other than numbers, period or backspace:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeparator = string.range(of: ".")
        
        let numbersSet = NSCharacterSet.decimalDigits
        let replacementTextIsANumber = string.rangeOfCharacter(from: numbersSet)
        
        if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
            return false
        } else if replacementTextIsANumber != nil || range.length == 1  { // if backspace, the range.length == 1
            return true
        } else {
            return false
        }
    }
#2

wow I guess I’m dumb…never would have got that…

#3

Thanks for showing how you completed this, to allow one decimal point I added an extra condition to the “or” statement

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeparator = string.range(of: ".")
        let replacementTextIsNumber = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits)
        print(range.length)
        
        if (existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil) {
            return false
        }
        else if replacementTextIsNumber != nil || replacementTextHasDecimalSeparator != nil || range.length == 1 { // Added condition to allow a decimal separator
            return true
        }
        else {
            return false
        }
    }