Search code examples
arraysswiftsavensuserdefaults

Save the multiply array Swift


I am tried to add more than one array but it delete old and create new one. How can I add more / insert another array to UserDefaults? Here my code:

let foodArray = ["Title": String(fShop_TitleInput.text ?? ""), "QTY": String(fShop_QTYInput.text ?? ""), "Price": String(fShop_PriceInput.text ?? "")]
        fShop_UserDefault.set(foodArray, forKey: "FoodArraySave")
        let getFoodArray = fShop_UserDefault.object(forKey: "FoodArraySave")
        print(getFoodArray ?? "No Array")

This work fine, but will save only one array at time. Example, I create new array title will be TestOne. If I add new title will be TestTwo, the array erase TestOne. How can I solve it?


Solution

  • As matt points out, your data is of type Dictionary, aka [String: Any]. Whenever you save it to UserDefaults, it gets overwritten, because you're writing to the same key. If you want to add more data to the same key, you'll have to convert your dictionary to an array of dictionaries: [[String: Any]]. Then you can access individual dictionaries by enumeration, or by accessing the particular index you're interested in.

    The other way would be to save each piece of data in a different key, like "FoodArraySave1", "FoodArraySave2", "FoodArraySave3". That's probably more involved and less efficient though.

    This is probably what you want to do:

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
    
    
            var myFoodData: [[String: Any]] = []
    
            let foodArray: [String: Any] = ["Title": "Eggs", "QTY": 18, "Price": 5.50]
            let foodArray2: [String: Any] = ["Title": "Bacon", "QTY": 12, "Price": 12.50]
    
            myFoodData.append(foodArray)
            UserDefaults.standard.set(myFoodData, forKey: "FoodArraySave")
    
            var getFoodData = UserDefaults.standard.object(forKey: "FoodArraySave") as! [[String: Any]]
    
            print(getFoodData[0])
    
            myFoodData.append((foodArray2))
            UserDefaults.standard.set(myFoodData, forKey: "FoodArraySave")
    
            getFoodData = UserDefaults.standard.object(forKey: "FoodArraySave") as! [[String: Any]]
    
            print(getFoodData[1])
        }