Search code examples
swiftxcodeswiftuinsuserdefaultsappstorage

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?


Solution

  • 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")
        }
    }