-1

if i wanted to locally store a value in a swift app in xcode like this:

   let name = "john doe"
   UserDefaults.standard.set(name , forKey: "User Name")

how would I test to see if there is already saved under that key in order to avoid saving the same thing twice or saving two things under the same key? is there a .doesExist sort of function the way theres a .isEmpty?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • You don't test. If there is something there, you are replacing it. It's your key, so it's your info; you can't go wrong. But note that UserDefaults is not "local" storage. It is _persistent_ storage; don't use it unless you need that. – matt Aug 24 '17 at 01:05
  • FYI - you can only store one value per key just like any dictionary. Of course that one thing can be an array if needed. – rmaddy Aug 24 '17 at 01:49

2 Answers2

0

You can use object(forKey:) to determine if any value is stored for a given key - it will return nil if there is no object stored for that key.

If you use any of the set functions then the current value (if any) for that key is replaced. It isn't possible for there to be two things saved under the one key.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
0

You can check if never define in specific key.

let newUserName = "john doe"
//check if already stored
if  let oldUsername = UserDefaults.standard.object(forKey: "User_Name") 
{
   //set new value of "User_Name" here
   print("\(oldUsername)")
} else {
   // set value of "User_Name" here
   UserDefaults.standard.set(newUserName , forKey: "User_Name")
}
Marosdee Uma
  • 719
  • 10
  • 14