-1

Check the condition and store the value from user default into variable and assign to textfield.

Initial condition in user default it will be empty I am checking the condition using guard if its empty (nil) assigning cost value to "" empty String else assign the value from user default which its stored from given defaultskey.cost

class  FirstViewControll : ViewController
var costValue: String?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       costValue! = userDefault.value(forKey: defaultsKeys.cost) as! String
            guard costValue != nil else {
                self.textField?.text = ""
                return
            }
           self.textField?.text = costValue!

}

App crashes for failing in optional value unwrap Fatal error: Unexpectedly found nil while unwrapping an Optional value

I assume that written a valid condition code.

KkMIW
  • 1,092
  • 1
  • 17
  • 27
  • costValue = userDefault.value(forKey: defaultsKeys.cost) as? String. Just replace this line worked perfect! Need to know after replacing "!" with "?" the string accept with optionals. – KkMIW Jul 24 '19 at 10:55

2 Answers2

4

You need to check if there is a value in UserDefaults.

if let value = userDefault.value(forKey: defaultsKeys.cost) as? String {
   // there is a value 
   costValue = value
} else {
   self.textField?.text = ""
}
Azat
  • 490
  • 2
  • 13
0

I removed guard checked with condition not exist ?? "" its worked fine!

self.textField?.text = userDefault.string(forKey: defaultsKeys.cost) ?? ""

No idea is this good approach or not!

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
KkMIW
  • 1,092
  • 1
  • 17
  • 27