Search code examples
swiftdictionarynsuserdefaults

Retrieving an array of dictionaries from UserDefaults


I'm trying to retrieve an array of dictionaries stored in UserDefaults but I can't figure our how best to do so.

Here is what I have so far:

let userDefaults = UserDefaults.standard
var userWorkouts: [Dictionary<String,String>] = []
userWorkouts = userDefaults.object(forKey: "SavedDict") as? [Dictionary<String,String>] 

Can someone point me in the right direction?


Solution

  • You've declared userWorkouts as a non-optional variable. But the expression userDefaults.object(forKey: "SavedDict") as? [Dictionary<String,String>] returns an optional array, hence the error message.

    You can change this to:

    userWorkouts = userDefaults.object(forKey: "SavedDict") as? [Dictionary<String,String>] ?? []
    

    Or reduce your three lines to just:

    var userWorkouts = UserDefaults.standard.object(forKey: "SavedDict") as? [Dictionary<String,String>] ?? []