[英]Swift fatal error: unexpectedly found nil while unwrapping an Optional value
I have textfield and i need to put inside session value and when i add gives me 我有文本字段,我需要放入会话值,添加时给我
fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil
error 错误
My codes here 我的代码在这里
@IBOutlet weak var discountField:UITextField!
func textFieldDidEndEditing(textField: MPGTextField_Swift, withSelection data: Dictionary<String,AnyObject>){
let displayDiscount : AnyObject? = data["discount"]
let addClientDiscount:String = (displayDiscount as? String)!
prefs.setObject(addClientDiscount, forKey: "addClientDiscount")
self.discountField.text = "\(addClientDiscount)" // THIS LINE GIVES ERROR
}
Also PROPERTLY Have ! 也正确地拥有! in referencing Outlets 在参考插座
Thanks 谢谢
Handle your line of error as follows: 如下处理错误行:
self.discountField.text = data!["discount"] as? String ?? ""
If data["discount"]
has a value, it will be assigned to the textfield, else an empty string will be used. 如果data["discount"]
具有值,则将其分配给文本字段,否则将使用空字符串。 But it will avoid the crash due to a nil
value. 但是它将避免由于nil
值导致的崩溃。
As suggested by many other guys, first check your IBOutlet connection. 正如许多其他人所建议的那样,首先检查您的IBOutlet连接。
If it's properly set, then put '?' 如果设置正确,请输入“?” after addClientDiscount as: 在addClientDiscount之后为:
self.discountField.text = "\(addClientDiscount?)"
Because if this line 因为如果这条线
let displayDiscount : AnyObject? = data["discount"]
gives nil
then crash may occur. 给出nil
则可能发生崩溃。
So to bypass that crash put '?' 因此,要绕过该崩溃,请输入“?”
UPDATE As suggested by Eric D. we can also do this: 更新正如Eric D所建议的,我们也可以这样做:
if let displayDiscount = data["discount"] {
let addClientDiscount = displayDiscount as! String
prefs.setObject(addClientDiscount!, forKey: "addClientDiscount")
self.discountField.text = "\(addClientDiscount!)"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.