Dev0urCode Dev0urCode - 1 month ago 7
Swift Question

UserDefaults checking for nil value not working

Any idea why my if statement always gives else answer ?
I noticed from the print that the object is stored as "optional()", maybe this optional state is different from nil ?

class ViewController: UIViewController {
@IBOutlet weak var phoneLabel: UITextField!
@IBOutlet weak var phoneDisplayLabel: UILabel!
@IBAction func storeButton(_ sender: Any) {
UserDefaults.standard.removeObject(forKey: "Nb")
UserDefaults.standard.set("\(phoneLabel.text!)", forKey: "Nb")
print (UserDefaults.standard.object(forKey: "Nb") as Any)
}

@IBAction func retrieveButton(_ sender: Any) {
let phoneNB = UserDefaults.standard.value(forKey: "Nb")
if let phoneNbDisplay = phoneNB as? String {
if UserDefaults.standard.object(forKey: "Nb") != nil {
phoneDisplayLabel.text = "Your NB is \(phoneNbDisplay)"
} else {
phoneDisplayLabel.text = "enter a number first"
}

}
}

Answer Source

try this

if (UserDefaults.standard.value(forKey: "etc") != nil)
{
    if (UserDefaults.standard.value(forKey: "etc") as! String).character.count == 0
    {
        //value is ""
    }else{
        //having some value
    }
}

enter image description here