SwiftDeveloper
SwiftDeveloper

Reputation: 7368

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

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

Upvotes: 0

Views: 1092

Answers (2)

Ishika
Ishika

Reputation: 2205

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.

Upvotes: 3

D4ttatraya
D4ttatraya

Reputation: 3412

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!)"
}

Upvotes: 1

Related Questions