【发布时间】:2021-07-05 17:44:10
【问题描述】:
我正在关注一个标记收藏夹的教程,他们忽略了如何加载和保存数据,所以如果你们能提供帮助,那就太好了。
这是我的代码:
class Favorites: ObservableObject {
private var task: Set<Int>
private let saveKey = "Favorites"
init() {
// load Saved data
self.task = []
}
func contains(_ sclocations: SClocation) -> Bool {
task.contains(sclocations.id)
}
func add(_ sclocations: SClocation) -> Bool {
objectWillChange.send()
task.insert(sclocations.id)
save()
}
func remove(_ sclocations: SClocation) -> Bool {
objectWillChange.send()
task.remove(sclocations.id)
save()
}
func save() {
// Write out Data
}
}
这是不断崩溃的部分:
Button(favorites.contains(sclocations) ? "Remove from Favorites" : "Add to Favorites") {
if self.favorites.contains(self.sclocations) {
self.favorites.remove(self.sclocations)
} else {
self.favorites.add(self.sclocations)
}
}
【问题讨论】: