0
votes

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

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

2
show the declaration of discountField... you probably didn't instanciate it.Woodstock
@Woodstock updated codes.SwiftDeveloper
Your IBOutlet is probably not properly connected in IB.Eric Aya
@SwiftDeveloper did you link your discountField to xib or storyboard properly?Breek
@SwiftDeveloper adding ! doesn't make it references properly, you have to check if there is a link between your IB and discountField. Btw, do you have multiple textField?Breek

2 Answers

3
votes

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. But it will avoid the crash due to a nil value.

1
votes

As suggested by many other guys, first check your IBOutlet connection.

If it's properly set, then put '?' after addClientDiscount as:

self.discountField.text = "\(addClientDiscount?)"

Because if this line

let displayDiscount : AnyObject? = data["discount"]

gives nil then crash may occur.
So to bypass that crash put '?'

UPDATE As suggested by Eric D. we can also do this:

if let displayDiscount = data["discount"] {
   let addClientDiscount = displayDiscount as! String
   prefs.setObject(addClientDiscount!, forKey: "addClientDiscount")

   self.discountField.text = "\(addClientDiscount!)"
}