One of the features of my app is the ability to "favorite" a Core Data item.
A favorite item gets a Image(systemName: "heart.fill")
and one that hasn't been favorited gets Image(systemName: "heart")
. I'm doing this with a simple comparison operator, like so:
Image(systemName: item.favorited ? "heart.fill" : "heart" )
.foregroundColor( item.favorited ? .red : .black)
I'd like to provide the option to switch from hearts to stars. (I know this isn't a dramatic or integral feature; it's more of a teaching exercise for myself to improve my skills.)
So I'd have in my app's settings the ability to choose between hearts or stars for favorites.
Obviously I'm not going to do this:
let x = hearts_or_stars_preference
Image(systemName: item.favorited ? ( x ? "heart.fill" : "star.fill" ) : ( x ? "heart" : "star" ) )
.foregroundColor( item.favorited ? .red : .black)
I could, but that's ugly. And what happens if I decide to also give users the ability to choose between hearts, stars, or checkmarks? Checkmarks aren't going to be "checkmark" and "checkmark.fill"; they'd be "checkmark.circle" and "xmark.circle".
Surely there's a good way to make this scalable. I'd like to be able to save an integer to UserDefaults
and then determine which image to display based on that. But here's where it gets a little tricky: Hearts are red, but stars are yellow. Checkmarks could be any color (although probably green). So I need to have a single integer that allows me to determine not only the image, but also the positive/negative color associated with it.
My gut is telling me that I'd use a class for this, but I fear that's because I've spent 20 years writing PHP.
Can anyone give me some advice here? Or point me to one of Paul's articles which covers this that I might have missed?
Thanks!