1- public struct StatsPublicizeInsight {
1+ public struct StatsPublicizeInsight : Codable {
22 public let publicizeServices : [ StatsPublicizeService ]
33
44 public init ( publicizeServices: [ StatsPublicizeService ] ) {
55 self . publicizeServices = publicizeServices
66 }
7+
8+ private enum CodingKeys : String , CodingKey {
9+ case publicizeServices = " services "
10+ }
711}
812
913extension StatsPublicizeInsight : StatsInsightData {
@@ -14,20 +18,17 @@ extension StatsPublicizeInsight: StatsInsightData {
1418 }
1519
1620 public init ? ( jsonDictionary: [ String : AnyObject ] ) {
17- guard
18- let subscribers = jsonDictionary [ " services " ] as? [ [ String : AnyObject ] ]
19- else {
20- return nil
21+ do {
22+ let jsonData = try JSONSerialization . data ( withJSONObject: jsonDictionary, options: [ ] )
23+ let decoder = JSONDecoder ( )
24+ self = try decoder. decode ( StatsPublicizeInsight . self, from: jsonData)
25+ } catch {
26+ return nil
2127 }
22-
23- let followers = subscribers. compactMap { StatsPublicizeService ( publicizeServiceDictionary: $0) }
24-
25- self . publicizeServices = followers
2628 }
27-
2829}
2930
30- public struct StatsPublicizeService {
31+ public struct StatsPublicizeService : Codable {
3132 public let name : String
3233 public let followers : Int
3334 public let iconURL : URL ?
@@ -39,18 +40,20 @@ public struct StatsPublicizeService {
3940 self . followers = followers
4041 self . iconURL = iconURL
4142 }
43+
44+ private enum CodingKeys : String , CodingKey {
45+ case name = " service "
46+ case followers
47+ }
4248}
4349
4450private extension StatsPublicizeService {
51+ public init ( from decoder: Decoder ) throws {
52+ let container = try decoder. container ( keyedBy: CodingKeys . self)
53+ let name = try container. decode ( String . self, forKey: . name)
54+ let followers = ( try ? container. decodeIfPresent ( Int . self, forKey: . followers) ) ?? 0
4555
46- init ? ( publicizeServiceDictionary dictionary: [ String : AnyObject ] ) {
47- guard
48- let name = dictionary [ " service " ] as? String ,
49- let followersCount = dictionary [ " followers " ] as? Int else {
50- return nil
51- }
52-
53- self . init ( name: name, followers: followersCount)
56+ self . init ( name: name, followers: followers)
5457 }
5558
5659 init ( name: String , followers: Int ) {
0 commit comments