So I have an app like the landmark app from apple.
I'm trying to figure out how to save the favorites, but I'm struggling with it.
I tried with save()
and with userDefaults
but with no result.
Some solutions use Toggle(isOn:)
, but the code doesn't use this.
The code from the landmark app is:
Button(action: {
self.userData.landmarks[self.landmarkIndex]
.isFavorite.toggle()
}) {
if self.userData.landmarks[self.landmarkIndex]
.isFavorite {
Image(systemName: "star.fill")
.foregroundColor(Color.yellow)
} else {
Image(systemName: "star")
.foregroundColor(Color.gray)
}
}
One of my attempts was the following:
Button(action: {
UserDefaults.standard.set(self.userData.landmarks[self.landmarkIndex]
.isFavorite.toggle(self.isFavorite, forKey: Bool)
)
}) {
if UserDefaults.standard.set(self.userData.landmarks[self.landmarkIndex])
.isFavorite {
Image(systemName: "star.fill")
.foregroundColor(Color.yellow)
} else {
Image(systemName: "star")
.foregroundColor(Color.gray)
}
I get an error 'Type of expression is ambiguous without more context'.
The button action is embedded in a navigationbaritem.
the code for userData is in the UserData.swift file:
import SwiftUI
final class UserData: ObservableObject {
@Published var showFavoritesOnly = false
@Published var landmarks = landmarkData
}
and
@EnvironmentObject var userData: UserData
is used in the landmarkdetail.swift file where the button action is placed