|
One of the features of my app is the ability to "favorite" a Core Data item. A favorite item gets a
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:
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 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! |
|
Use an enum for something like this.
And then you would do:
Since the enum conforms to
|
|
Thanks, @roosterboy! That appears to be exactly what I need. But how do I force it to not be optional? Before even attempting to associate it with a
But when I use it -- e.g.
I don't want to have to sprinkle a bunch of question marks and exclamation points all over the place. What am I doing wrong? |
|
You aren't doing anything wrong. It's a consequence of One way you could handle that would be to supply a default value for
Then when you assign a
And now |
|
Brilliant! Thank you so much, @roosterboy. And double extra thank you for explaining the optionals bit. I never understood that about Int and now it makes sense. |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.