2

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!

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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")

Comments

1

Instead of this:

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

do this:

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

This will initialize the array to an empty array in the case that it does not yet exist in the defaults database (or if it's corrupt in some way that it won't resolve to an array of Ints).

Avoiding the use of as! here is good practice anyway, since otherwise you're going to crash on read if your defaults become corrupt.

4 Comments

This did work at first, but then whenever the app is closed and opened again, the array goes back to empty...
@JacobCavin Are you writing the modified array back to the user defaults after adding something to it?
@CharlesSrstka I have the same problem
@JacobCavin I have the same problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.