UserDefaults won't retrieve my string array correctly

I am trying to make a mechanism that lets users save items to favourites (which is an array) and then save that to UserDefaults, however I can't seem to get it to write to UD correctly. Printing UDSaved in the example below returns [], even though I just appended an element to the array.

Does anyone have an idea what I'm doing wrong?

Is it a syntax error and I am not retrieving this correctly or is there a problem with my logic?

var favouritesArray: [String] = []

func UDWrite() {UserDefaults.standard.set(favouritesArray, forKey: "UDfavouritesArray")}
let UDSaved = UserDefaults.standard.stringArray(forKey: "UDfavouritesArray") ?? [String]()


favouritesArray.append("element")
UDWrite()

print(UDSaved)
arraysswiftnsuserdefaults

Answers

answered 3 months ago Herr der Töne #1

As some stated in the comments: UDSaved never get's updated. My solution would be to make UDSaved a function like so:

var favouritesArray: [String] = []

func UDWrite() {UserDefaults.standard.set(favouritesArray, forKey: "UDfavouritesArray")}
func UDSaved() -> [String] {return UserDefaults.standard.stringArray(forKey: "UDfavouritesArray") ?? [String]}()

favouritesArray.append("element")
UDWrite()

print(UDSaved())

Or you could make it a computed property

var UDSaved: [String] {
   return UserDefaults.standard.stringArray(forKey: "UDfavouritesArray") ?? [String]
}

comments powered by Disqus