Guest User

Untitled

a guest
Jan 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import UIKit
  2.  
  3. struct Color: Codable {
  4. var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
  5.  
  6. var uiColor : UIColor {
  7. return UIColor(red: red, green: green, blue: blue, alpha: alpha)
  8. }
  9.  
  10. init(uiColor : UIColor) {
  11. uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  12. }
  13. }
  14.  
  15. struct Task: Codable {
  16.  
  17. private enum CodingKeys: String, CodingKey { case color }
  18.  
  19. var color : UIColor
  20.  
  21. init(content: String, deadline: Date, color : UIColor) {
  22. self.color = color
  23. }
  24.  
  25. init(from decoder: Decoder) throws {
  26. let container = try decoder.container(keyedBy: CodingKeys.self)
  27. color = try container.decode(Color.self, forKey: .color).uiColor
  28. }
  29.  
  30. public func encode(to encoder: Encoder) throws {
  31. var container = encoder.container(keyedBy: CodingKeys.self)
  32. try container.encode(Color(uiColor: color), forKey: .color)
  33. }
  34. }
  35.  
  36. extension UIColor {
  37. convenience init(hex: String) {
  38. let removeBadChar = hex.replacingOccurrences(of: "#", with: "")
  39. let hexNumber = Int(removeBadChar, radix: 16)!
  40.  
  41. let red = CGFloat((hexNumber >> 24) & 0xff) / 255.0
  42. let green = CGFloat((hexNumber >> 16) & 0xff) / 255.0
  43. let blue = CGFloat((hexNumber >> 8) & 0xff) / 255.0
  44. let alpha = CGFloat((hexNumber) & 0xff) / 255.0
  45.  
  46. self.init(red: red, green: green, blue: blue, alpha: alpha)
  47. }
  48. }
  49.  
  50. let colorString = "#F01F74FF"
  51. //Int(colorString, radix: 16)
  52.  
  53. let newColor = UIColor(hex: colorString)
  54.  
  55.  
  56. let task = Task(content: "Foo", deadline: Date(), color: newColor)
  57. do {
  58. let data = try JSONEncoder().encode(task)
  59. print(String(data: data, encoding: .utf8)!)
  60. let newTask = try JSONDecoder().decode(Task.self, from: data)
  61. print(newTask)
  62. } catch { print(error) }
Add Comment
Please, Sign In to add comment