Search code examples
swiftswiftuiuserdefaults

How can I append an new Element to an Array in the Userdefaults (SwiftUI)


I wanna have an String Array in the Userdefaults, which I can edit. That means I want to append new Items to this Array.Here is some example Code

var defaults = UserDefaults.standard
defaults.array(forKey: "myArray")?.append("NewElement")

But I get this Error Code:

Cannot use mutating member on immutable value: function call returns immutable value

How can I handle that? Do you need more information? Thanks for your time Boothosh


Solution

  • You need to assign the result of the function to variable before you can modify it

    if var array = defaults.array(forKey: "myArray") {
         array.append("NewElement")
    }