arraysswiftpermanent

How to add value to user default array with swift 4


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 = [""]

        }
    }

Solution

  • 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.