Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- 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)
- }
- }
- struct Task: Codable {
- private enum CodingKeys: String, CodingKey { case color }
- var color : UIColor
- init(content: String, deadline: Date, color : UIColor) {
- self.color = color
- }
- init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- color = try container.decode(Color.self, forKey: .color).uiColor
- }
- public func encode(to encoder: Encoder) throws {
- var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(Color(uiColor: color), forKey: .color)
- }
- }
- extension UIColor {
- convenience init(hex: String) {
- let removeBadChar = hex.replacingOccurrences(of: "#", with: "")
- let hexNumber = Int(removeBadChar, radix: 16)!
- let red = CGFloat((hexNumber >> 24) & 0xff) / 255.0
- let green = CGFloat((hexNumber >> 16) & 0xff) / 255.0
- let blue = CGFloat((hexNumber >> 8) & 0xff) / 255.0
- let alpha = CGFloat((hexNumber) & 0xff) / 255.0
- self.init(red: red, green: green, blue: blue, alpha: alpha)
- }
- }
- let colorString = "#F01F74FF"
- //Int(colorString, radix: 16)
- let newColor = UIColor(hex: colorString)
- let task = Task(content: "Foo", deadline: Date(), color: newColor)
- do {
- let data = try JSONEncoder().encode(task)
- print(String(data: data, encoding: .utf8)!)
- let newTask = try JSONDecoder().decode(Task.self, from: data)
- print(newTask)
- } catch { print(error) }
Add Comment
Please, Sign In to add comment