Search code examples
swiftuserdefaults

How to store and retrieve data in userdefault? (Ex:Array of Struct )


struct ExpandableNames:Codable {
    var isExpanded: Bool
    var names: [String]
    var icons: [String]
} 

var names = ["Food/Drink", "Tours", "Transport", "Gifts","Flights", "Shopping", "Activities","Entertainment","Accomodation","Other"]
var icons = ["Food_Category", "Tours", "Transport_Category", "Gifts_Category","Flights_Category","Shopping_Category","Activities_category","Entertainment_category", "Accomodation_Category","Other_Category"]

var categoryWholeArray = [Int:ExpandableNames]()

How to store categoryWholeArray to user default?

I tried

Store userDefault:

 UserDefaults.standard.set(try? PropertyListEncoder().encode(categoryWholeArray), forKey:"categoryWholeArray")

Retrieve data problem is here

   if let data = UserDefaults.standard.value(forKey:"categoryWholeArray") as? Data {
                      let songs2 = try? PropertyListDecoder().decode(Array<categoryWholeArray.values>.self, from: data)
}

Anyone tried?


Solution

  • All correct except

    if let data = UserDefaults.standard.value(forKey:"categoryWholeArray") as? Data {
        let songs2 = try? PropertyListDecoder().decode([Int:ExpandableNames].self, from: data)
        print(songs2)
    }