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"
}
}
}
Aucun commentaire:
Enregistrer un commentaire