Search code examples
iosnsuserdefaultsswift3swiftyuserdefaults

Swift Adding Value to Existing User Defaults Value


I got User Defaults with the key "abc" for example and it contains a string.

The last string stored in this key is "aaa".

Now, I want to store an additional value for this key, but I don't want to delete the last value "aaa" because I need it.

I want to have an Array of strings contains at the second retreive: ["aaa","some_other_value", "some_other_value2"...].

This is my code so far to store the information in user defaults:

self.user_defaults.set(self.myTextField.text, forKey:"asd")

This is the code for get the data:

if let arr = user_defaults.string(forKey:"asd"){
    print (arr)
}

Solution

  • Try follwing code for save new value :

    if let arr = user_defaults.array(forKey: "asd")
            {
                var arrvalues = arr as! [String]
                arrvalues.append(self.myTextField.text)
                self.user_defaults.set(arrvalues, forKey:"asd")
                self.user_defaults.synchronize()
                print (arr)
            }
            else
            {
                self.user_defaults.set([self.myTextField.text], forKey:"asd")
            }
    

    This is the code for get the data:

    if let arr = user_defaults.array(forKey:"asd"){
        print (arr)
    }