Colourful array of umbrellas

A Simple Approach to Saving Color in CoreData with SwiftUI

Tianna Lewis

--

In my latest SwiftUI project I needed to save user-selected Colors into CoreData. Users would interact with the SwiftUI ColorPicker (love this thing by the way) to build a custom tag identifier with a custom background colour (no that’s not a typo, in Canada colour is spelled with the letter u). I went looking for an elegant way to achieve this aim, but after reading a handful of articles and Stack Overflow questions on the matter I couldn’t get all the pieces in place the right way to work. I settled on a solution that isn’t as clever but ultimately works for my purposes.

So what was the approach I took?

To get to the point I opted for saving the individual red, green, blue, and alpha values into Core Data and then building the colour back up from these values when needed.

First I created a Color Extension that would get the individual components out of a Color for me.

Then the next step was to save this into Core Data, which is handled by the CreateTagViewModel.

So when the view calls the function the new object is saved into Core Data.

And when I want to use the colour that was saved I build it back out using the constructor built into Color.

I do want to eventually double back and figure out this more elegant solution but for now, this works for me. I find when working on a new project prototype sometimes I can get too concerned with certain problems, sometimes sinking hours (or worse days) into solving a problem in a novel way which best case slows me down, but the worst-case has me abandoning a project altogether. So as not to fall victim to yet another abandoned project I decided to keep it simple and move on.

Everything being said, I would be lying if I didn’t say that I am open to changing things, so if you have any suggestions I would love to hear them.

--

--

Tianna Lewis

Learning and Building in the Open. Check out what I’ve been up to at tiannahenrylewis.com.