3

I'm trying to get from UserDefaults a Bool whose key depends on the nameID of a Product.

I tried this way:

import SwiftUI

struct ProductDetail: View {
    
    var product: GumroadProduct
    
    @AppStorage("LOCAL_LIBRARY_PRESENCE_PRODUCTID_\(product.id)") var isLocal: Bool = false
    
    var body: some View {
       Text("ProductView") 
    }
}

Anyway Swift throws this error:

Cannot use instance member 'product' within property initializer; property initializers run before 'self' is available

I understand why Swift is throwing that error but I don't know how to get around it.

Is there a solution?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Albifer
  • 167
  • 2
  • 10
  • Are you sure UserDefaults is the right solution for this if you need to store a value per product? – Joakim Danielson Sep 15 '21 at 16:27
  • It’s a personal project so Products won’t be more than 20 but if you believe there’s a more valid alternative let me know. – Albifer Sep 15 '21 at 16:59
  • One solution is to add `isLocal` as a property to GumroadProduct, another could be to store an array of id's for products that are local in UserDefaults (unless this changes very frequently) – Joakim Danielson Sep 15 '21 at 17:20

1 Answers1

3

Here is a solution for your code snapshot - provide explicit initialiser and instantiate properties in it depending on input:

struct ProductDetail: View {

    @AppStorage private var isLocal: Bool
    private var product: GumroadProduct

    init(product: GumroadProduct) {
        self.product = product
        self._isLocal = AppStorage(wrappedValue: false, "LOCAL_LIBRARY_PRESENCE_PRODUCTID_\(product.id)")
    }

    var body: some View {
        Text("ProductView")
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690