Search code examples
swiftswiftuiswiftui-listswiftui-foreach

SwiftUI How to make ForEach with Dict with array of custom objects auto update


I have a dict with arrays of custom classes, defined like this:

var coupons: [String: [Coupon]]

And I put them into a ForEach like this:

List {
                        
        ForEach(keys, id: \.self) { key in
                Section(header: Text(key)) {
                    ForEach(couponDict[key] ?? [], id: \.id) { coupon in
                            Button(ifexpiredString(date: coupon.date)+coupon.data[1]) {
                                     let coupons = UserDefaults.standard.coupons
                                     let couponIndex = coupons.firstIndex(of: coupon)
                                     self.currentview = "Coupon"+String(couponIndex!)
                            }.foregroundColor(ifexpired(date: coupon.date) ? Color.gray : ifexpireing(date: coupon.date))
                   }
           }
     }
}

I've read many answers on making an auto-updating ForEach or List, but none using a dictionary with an array of custom objects stored under each key. Worse, I'm drawing couponDict from UserDefaults. How can I make this List or ForEach auto-update itself?


Solution

  • try something like this:

    List {
        ForEach(Array(coupons.keys), id: \.self) { key in 
        // or ForEach(coupons.keys.sorted(), id: \.self) { key in 
            Section(header: Text(key)) {
                ForEach(coupons[key] ?? [], id: \.id) { coupon in
                    Button(ifexpiredString(date: coupon.date)+coupon.data[1]) {
                        let coupons = UserDefaults.standard.coupons
                        let couponIndex = coupons.firstIndex(of: coupon)
                        self.currentview = "Coupon"+String(couponIndex!)
                    }.foregroundColor(ifexpired(date: coupon.date) ? Color.gray : ifexpireing(date: coupon.date))
                }
            }
        }
    }