Var of type color inside swift data model

Hi, I am trying to create a variable of type Color inside the swift data model in Xcode playground . This gives me these errors :

  1. No exact matches in call to instance method 'setValue'
  2. No exact matches in call to instance method 'getValue'
  3. No exact matches in call to instance method 'setValue'

What is the problem?

Hello :)

SwiftData only supports primitive types (Int, Bool, ...) currently, so there is no possibility to save a color itself at the moment. In order to save a color you can choose different approaches. For example, you could define a SwiftData Model to save the different values of red, green, blue and alpha like this:

final class ColorModel {
    var red: CGFloat
    var green: CGFloat
    var blue: CGFloat
    var alpha: CGFloat
    
    init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        self.red = red
        self.green = green
        self.blue = blue
        self.alpha = alpha
    }
}

Then you can display your colors through the following code (simplified here in a ForEach(), has to be adjusted):

ForEach(colors, id: \.self) { color in
    Color(UIColor(red: color.red, green: color.green, blue: color.blue, alpha: color.alpha))
}

If you have any further questions, don't hesitate to ask. I hope I was able to help you.

Var of type color inside swift data model
 
 
Q