1

I have a model in Swift that looks like:

import Foundation
import SwiftUI

struct Note: Hashable, Codable {

    var title: String
    var createdDate: Date
    var notes: String
    var color: Color

    var niceDate: String {
        let dateformatter = DateFormatter()
        dateformatter.dateStyle = .medium
        return dateformatter.string(from: self.createdDate)
    }
}

Now, it can't conform to codable because Color doesn't conform. However, I cannot extend it otherwise it gives me the error Implementation of 'Encodable' cannot be automatically synthesized in an extension in a different file to the type

How can I make Note (with the color attribute) conform to Codable? Ideally it could be applied to other builtin types as well.

  • I don't think currently SwiftUI provides a way to get the RGB values (or `UIColor`) from a `Color` view. If you search, there are some hacky ways to do it, but basically that's what you would need to encode it. Decoding is easier, because you could easily instantiate it from something like RGBA values – New Dev Jun 11 '20 at 01:11

1 Answers1

0

One of the solutions is to make Color conform to Codable:

struct Color: Codable {
    var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0

    var uiColor: UIColor {
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }

    init(uiColor: UIColor) {
        uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
    }
}

This works if you're interested in RGB and alpha components only. If you need more, you can use this wrapper originally proposed here.

Note: You may need to explicitly implement Equatable and Hashable protocols as well.

pawello2222
  • 46,897
  • 22
  • 145
  • 209