Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - @AppStorage variable key value

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?

like image 568
Albifer Avatar asked Oct 18 '25 19:10

Albifer


1 Answers

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")
    }
}
like image 65
Asperi Avatar answered Oct 21 '25 11:10

Asperi