-2

I have a reset function that sets an empty string for every key in UserDefaults.standard but it isn't actually resetting them, sometimes it works, sometimes it doesn't, and the weird thing is that sometimes it reset only a few values.

There's nothing that could set the previous values because the reset function once the values are reset, exit the application.

@IBAction func reset(_ sender: Any) {
    //(userDefaults = UserDefaults.standard)
    userDefaults.set("", forKey: "ident")
    userDefaults.set("", forKey: "usr")
    userDefaults.set("", forKey: "psw")
    userDefaults.set("", forKey: "token")
    userDefaults.set("", forKey: "release")
    userDefaults.set("", forKey: "expire")
    userDefaults.set("", forKey: "name")
    userDefaults.set("", forKey: "surname")
    userDefaults.set("", forKey: "ident_req")
    print(userDefaults.string(forKey: "ident")) //output: Optional("")
    exit(1)
}

What should I do??

cam0347
  • 23
  • 3

2 Answers2

1

Your code above seems to be working properly. You are setting an empty string to the value of "ident" and checking it a bit after at which point according to your question you're getting

Optional("")

The value inside the optional is correct (aka. an empty string ""). The reason why you're getting an optional is because the return value of stringForKey could potentially be nil, and therefore it returns an optional.

I wouldn't normally recommend force unwrapping but if you're just setting it a few lines above, and all you want is to print it you can do:

print(userDefaults.string(forKey: "ident")!)

which will print the empty string "" exactly as you're setting it on the first line in the function.

Lastly, you'd probably be better off removing the value with removeObject(forKey:) instead of setting it to an empty string. They are different things, and I believe you're trying to represent that there is nothing there instead of an empty string which is actually a value.

Jacobo Koenig
  • 11,728
  • 9
  • 40
  • 75
  • Not sure what you mean by "not working." Like I said in the post, the system is doing exactly what you're asking it to from what you've posted above. – Jacobo Koenig Dec 26 '19 at 19:10
0

Try

UserDefaults.standard.set(nil , forKey: "Your_Key")

to save empty the UserDefaults And while fetching it use

UserDefaults.standard.string(forKey:"You_Key")

Nayan Dave
  • 1,078
  • 1
  • 8
  • 30