@@ -13,9 +13,16 @@ extension ColorSection: IdentifiableSection {
1313 var sectionIdentifier : String { return title }
1414}
1515
16+ extension ColorSection : Decodable {
17+ enum CodingKeys : String , CodingKey {
18+ case title
19+ case items = " colors "
20+ }
21+ }
22+
1623// MARK: Items
1724
18- struct ColorItem : Equatable {
25+ struct ColorItem {
1926 let name : String
2027 let rgb : ( CGFloat , CGFloat , CGFloat )
2128
@@ -24,7 +31,36 @@ struct ColorItem: Equatable {
2431 }
2532}
2633
27- func == ( lhs: ColorItem , rhs: ColorItem ) -> Bool {
28- return lhs. name == rhs. name && lhs. rgb == rhs. rgb
34+ extension ColorItem : Equatable {
35+ static func == ( lhs: ColorItem , rhs: ColorItem ) -> Bool {
36+ lhs. name == rhs. name && lhs. rgb == rhs. rgb
37+ }
2938}
3039
40+ extension ColorItem : Decodable {
41+ enum Errors : Error {
42+ case rgbDecodingFailure
43+ }
44+ enum CodingKeys : String , CodingKey {
45+ case name
46+ case rgb
47+ }
48+
49+ init ( from decoder: Decoder ) throws {
50+ let container = try decoder. container ( keyedBy: CodingKeys . self)
51+ name = try container. decode ( String . self, forKey: . name)
52+ let scanner = try Scanner ( string: container. decode ( String . self, forKey: . rgb) )
53+ guard
54+ scanner. scanCharacters ( from: . init( charactersIn: " # " ) ) == " # " ,
55+ let rgbUInt64 = scanner. scanUInt64 ( representation: . hexadecimal)
56+ else {
57+ print ( " Name: \( name) \n RGBString: \( scanner. string) " )
58+ throw Errors . rgbDecodingFailure
59+ }
60+ rgb = (
61+ CGFloat ( ( rgbUInt64 & 0xff0000 ) >> 16 ) / 255 ,
62+ CGFloat ( ( rgbUInt64 & 0x00ff00 ) >> 8 ) / 255 ,
63+ CGFloat ( ( rgbUInt64 & 0x0000ff ) >> 0 ) / 255
64+ )
65+ }
66+ }
0 commit comments