<unknown>:0: error: key path value type in swiftUI

I have a propertyWrapper:

import UIKit
@propertyWrapper struct AutoSaveWrapper<T: Codable & Collection> {
    private var defaultKey: String
    
    var wrappedValue: T {
        didSet {
            self.save()
        }
    }

    private func save() {
        do {
            UserDefaults.standard.set(try PropertyListEncoder().encode(self.wrappedValue), forKey: self.defaultKey)
        } catch {
            print("AutoSaveWrapper save error: \(error)")
        }
    }
    
    init(wrappedValue: T, defaultKey: String) {
        self.defaultKey = defaultKey
        
        defer { self.save() }
        
        guard let data = UserDefaults.standard.object(forKey: self.defaultKey) as? Data else {
            self.wrappedValue = wrappedValue
            return
        }
        
        do {
            self.wrappedValue = try PropertyListDecoder().decode(T.self, from: data)
        } catch {
            print("AutoSaveWrapper load error: \(error)")
            self.wrappedValue = wrappedValue
        }
    }
}

I want to use it as @EnvironmentObject, therefore, I wrapped it in a class of inheriting from ObservableObject:

class UserData: ObservableObject {
    @Published
    @AutoSaveWrapper(defaultKey: "cats")
    var cats: [ItemCatergory<String>] = []

    @Published
    var voiceOn = true
}

but i got this error:

<unknown>:0: error: key path value type '[ItemCatergory<String>]' cannot be converted to contextual type 'AutoSaveWrapper<[ItemCatergory<String>]>'

But i don't have error if I use @State @AutoSaveWrapper(defaultKey: "cats") var cats: [ItemCatergory<String>] = [] in View struct.

1 Like

Did you ever find the cause of this, or a solution? I'm running into the same issue, and it's forcing me to use a regular generic struct instead of a property wrapper.

Terms of Service

Privacy Policy

Cookie Policy