swift - 由于 uiTextfield 中没有值,应用程序崩溃

标签 swift uitextfield

当我在 UiTextField 中输入值并按添加按钮时,应用程序运行得很好,但是当我不在 UiTextField 中输入值时,然后按添加按钮,整个应用程序就会崩溃。有人可以帮助我并给我带来光明吗?提前感谢您并祝您和您的家人良好的祝愿。

这是我的代码

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.textFild.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet var textFild: UITextField!

    @IBAction func ButtonAwesome(sender: AnyObject) {



        let value:Double = Double(textFild.text!)!


        let sum:Double = value - 1;



        let alert = UIAlertController(title: "km", message:  "\(sum)", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Exit", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert,animated: true, completion: nil)



    }


    func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString stringer: String) -> Bool
    {

        if (textField.text == "" && (stringer == ".")) {
            return false;
        }


        let countdots = textField.text!.componentsSeparatedByString(".").count - 1

        if countdots > 0 && stringer == "."
        {
            return false
        }


        return true
    }




}

最佳答案

更可靠的解决方案是使用 nil 合并运算符来断言 value 的初始化永远不会失败。

@IBAction func ButtonAwesome(sender: AnyObject) {
    let value = Double(textFild.text ?? "0") ?? 0
    let sum:Double = value - 1;

    let alert = UIAlertController(title: "km", message:  "\(sum)", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Exit", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert,animated: true, completion: nil)
}

这对于 textField.text 的以下任何“意外”值均有效:nil""(空)或某些不能用于初始化 Double 类型变量的字符(例如 "a")。对于所有这些情况,value 的值为 0


作为示例,请考虑以下解决初始运行时异常的安全方法和不安全方法之间的比较。

我们首先看看强制展开选项的危险 - 这不是一个安全的解决方案。如果 textField.text 包含 nil 或非数字字符(例如“一个”?结果:

var myTextFieldText : String? = nil

/* Example 1: nil value causes runtime error */
if myTextFieldText != "" { // this is 'true' -> enter if closure
    let value:Double = Double(myTextFieldText!)!
    /* this will fail at run time since we are forcibly (un-safely)
       unwrapping an optional containing 'nil'                           */
}

/* Example 2: non-numeric string character causes runtime error */
myTextFieldText = "a"
if myTextFieldText != "" { // this is 'true' -> enter if closure
    let value:Double = Double(myTextFieldText!)!
    /* this will fail at run time since we cannot initalize a
       Double with a string value "a", hence 'Double(myTextFieldText!)'
       returns nil, but since we've appended '!', we, like above,
       forcibly tries to unwrap this optional of value nil              */
}

通常,您应该始终使用选项的条件展开,以避免在强制展开选项时遇到 nil 值,后者会导致运行时错误。

上面示例的更强大的版本,使用 nil 合并运算符:

myTextFieldText = nil

let valueA = Double(myTextFieldText ?? "0") ?? 0 // 0
/* OK, Double(myTextFieldText ?? "0") = Double("0") = 0                  */

myTextFieldText = "a"
let valueB = Double(myTextFieldText ?? "0") ?? 0 // 0
/* OK, Double(myTextFieldText ?? "0") = Double("a") = nil (fails)
    => use rhs of outer '??' operator: nil ?? 0 = 0                      */

对于另一种方法,您可以扩展 UITextField 来满足字符串到数字类型转换的需求,请参阅以下线程中的 Leos 简洁答案:

该帖子还包含一些其他有值(value)的见解。从 UITextField 实例中将文本读取为数值。


最后,在处理 String 到 Double 值转换时,使用固定精度可能是合适的。生成的 Double 值中的小数位数。有关如何使用 NSNumberFormatter 和扩展执行此操作的完整示例,请参阅:

关于swift - 由于 uiTextfield 中没有值,应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34704979/

相关文章:

swift - tableview 单元格上的详细文本标签不会使用倒数计时器刷新

ios - 点击时 iAd 横幅未加载

ios - 仅在验证输入后启用 UIAlertController 的 UIAlertAction

ios - 设置自定义 UITextField 最大长度

swift - 长按使用约束更新放大

swift - Swift 中的精确字符串格式说明符

swift - 不允许使用字符串常量 NSLinguisticTagNoun 的枚举

objective-c - 通过触摸 UITableView 的背景隐藏键盘

ios - 调用文本字段 :shouldReplaceCharactersInRange from a delegate method

cocoa-touch - iOS : bubble text?