Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to UserDefaults Array (Swift)

I want to create an array of Ints that I can append to and will be saved to UserDefaults so that next time the user opens the app, the array will be saved. So, I know how to create a UserDefaults array...

var intArray = UserDefaults.standard.array(forKey: "intArray") as! [Int]

and I know how to set the array to an already existing array:

var array = [2, 6, 34, 4, 9]
UserDefaults.standard.set(array, forKey: "intsArray")

But, I need the array to be empty and then the user adds Ints to the array. Thanks for your help!

like image 820
Jacob Cavin Avatar asked Jun 22 '26 04:06

Jacob Cavin


2 Answers

I would suggest you to create a computed property for this purpose:

var intArray: [Int] {
    get {
        return UserDefaults.standard.array(forKey: "intArray") as? [Int] ?? []
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "intArray")
    }
}

Now whenever you modify your intArray it will update its value in UserDefaults and whenever you call intArray it returns you the value from UserDefaults.

like image 67
Ruslan Serebriakov Avatar answered Jun 23 '26 19:06

Ruslan Serebriakov


Not sure about what you need.

However this is how you add an empty array to UserDefaults

 UserDefaults.standard.set([Int](), forKey: "nums")

And this is how you

  1. load the array from UserDefaults
  2. add a value
  3. save it again to UserDefaults

.

var nums = UserDefaults.standard.array(forKey: "nums") as! [Int]
nums.append(1)
UserDefaults.standard.set(nums, forKey: "nums")
like image 33
Luca Angeletti Avatar answered Jun 23 '26 18:06

Luca Angeletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!