CristianMoisei
CristianMoisei

Reputation: 2279

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)

Upvotes: 3

Views: 128

Answers (1)

Herr der Töne
Herr der Töne

Reputation: 178

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]
}

Upvotes: 3

Related Questions