简体   繁体   中英

Type 'Favorites.Type' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols

Please tell me what could be the problem with this error and how to fix it?

I'm use SwiftUI 2.0

"Type 'Favorites.Type' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols"

Code:

class Favorites: ObservableObject {

private var tasks: Set<String>
let defaults = UserDefaults.standard

init() {
    let decoder = JSONDecoder()
    if let data = defaults.value(forKey: "Favorites") as? Data {
        let taskData = try? decoder.decode(Set<String>.self, from: data)
        self.tasks = taskData ?? []
    } else {
        self.tasks = []
    }
}

func getTaskIds() -> Set<String> {
    return self.tasks
}

func isEmpty() -> Bool {
    tasks.count < 1
}

func contains(_ task: dataTypeFont) -> Bool {
    tasks.contains(task.id)
}

func add(_ task: dataTypeFont) {
    objectWillChange.send()
    tasks.insert(task.id)
    save()
}

func remove(_ task: dataTypeFont) {
    objectWillChange.send()
    tasks.remove(task.id)
    save()
}

func save() {
    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(Favorites)  {
        defaults.set(encoded, forKey: "Favorites")
    }
}

}

Screenshot Error: Error

Typo.

According to the load method you have to encode tasks not the class type

func save() {
    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(tasks)  {
        defaults.set(encoded, forKey: "Favorites")
    }
}

And don't use value(forKey: with UserDefaults , there is a dedicated method

if let data = defaults.data(forKey: "Favorites") {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM