0

I'm trying to append and save a series of strings using UserDefaults, but my code is replacing the data instead of adding to the array every time its called, what am I missing?

if Plus == true
    {

        if typeOfMath != [""]
        {

        typeOfMath.append("Addition")
        UserDefaults.standard.set(typeOfMath, forKey: "typeMath")
        print ("\(typeOfMath)")
        typeOfMath = [""]

        }
    }
Daniel.wu
  • 31
  • 1
  • 5

1 Answers1

1

Since you try to set the value in UserDefaults each time, it actually overwrites the value for the key.

What you need to do is :

  1. Read the existing array in UserDefaults
  2. Append new value to this array
  3. Write this array back to UserDefaults.
NSAdi
  • 1,243
  • 9
  • 19
  • Got it! thank you! I added if var mathData = UserDefaults.standard.stringArray(forKey: "typeMath") { mathData.append("\(typeOfMath)") typeOfMath = mathData } my data looks like this: ["Addition", "[\"Addition\"]", "[\"Addition\"]"], how do i get rid of the brackets so it will look like ["Addition", "Addition", "Addition"] ? – Daniel.wu Oct 15 '17 at 04:55
  • @Daniel.wu I think you can use this `mathData.append(contentsOf: typeOfMath)` – 3stud1ant3 Oct 15 '17 at 05:41