避免在约束字符集期间双重时期崩溃



我有一个我接近完美的GPA计算器项目。尽管" .0123456789"是唯一的允许字符,但我仍需要防止用户输入非浮动数。例如,如果用户输入2.3。无论出于何种原因,我的程序都会崩溃,因为此"输入"不是浮点。我在下面包含了我的代码的基础。

func textField(_ textField: UITextField, shouldChangeCharactersIn     range: NSRange, replacementString string: String) -> Bool {
    var allowed = CharacterSet.decimalDigits
    let period = CharacterSet.init(charactersIn: ".")
    allowed.formUnion(period)
    //UNCOMMENT when isSuperset is working
    //let characterSet = CharacterSet(charactersIn: string)
    //return allowed.isSuperset(of: characterSet)
    // Swift 3 appropriate solution
    let isSuperset = string.rangeOfCharacter(from: allowed.inverted) == nil
    return isSuperset
}

@IBAction func Calculate(_ sender: AnyObject) {
    // if not filled in
    if Credits1TF.text == "" || Grade1TF.text == "" || CumCredits.text == "" || CumGPA.text == "" || Credits1TF.text == "." || Grade1TF.text == "." || CumCredits.text == "." || CumGPA.text == "."
    {
 print...         
}            else 
        {
            //credits
            let credit1 = Float(Credits1TF.text!)!
            //grades
            let grade1 = Float(Grade1TF.text!)!
            //math
            let firstgrade = credit1 * grade1

与TextField函数有关的最实际上最实际在文本字段中仅添加一个小数点的接受是如何添加一个小数点?还是有更简单/直接的方式?

更新1:

   let credit1 = Float(Credits1TF.text!)!
            if credit1 != nil
            {
                let newcredits1 = credit1
            //grades
            let grade1 = Float(Grade1TF.text!)!
                if grade1 != nil
                { let newgrade1 = grade1

除非我不正确地执行此操作,否则我会收到警告,即"将'float'的非偏见价值与nil进行比较始终返回true"。我的印象是,如果Credits1或Garth1!= nil,我的数值值得,并且以后不会导致崩溃。

func textField(_ textField: UITextField, shouldChangeCharactersIn     range: NSRange, replacementString string: String) -> Bool {
    var allowed = CharacterSet.decimalDigits
    let period = CharacterSet.init(charactersIn: ".")
    allowed.formUnion(period)

    if (textField.text?.contains("."))! && string.contains(".")
    {
        return false
    }
    else
    {
        let isSuperset = string.rangeOfCharacter(from: allowed.inverted) == nil
        return isSuperset
    }

}

此代码将接受的字符限制为" 0-9",还允许输入一个周期/小数点。在if语句的其他部分中可以看到0-9个字符的返回。在以前的问题中,拉吉(Raj

相关内容

  • 没有找到相关文章

最新更新