4

I'm having some trouble with conforming 2 protocols together using the Codable protocol.

My understanding is that even if I used a custom object, as long as that object successfully conforms to Codable, then any object referencing that can also conform.

I have the following code and cannot see why I am getting the errors:

import UIKit
import Foundation

protocol PromotionProtocol: Codable {
    var promotionType: Int? { get }
    var promotionCode: String? { get }
    var fileName: String? { get }
    var facetDescription: String? { get }
    var promoDescription: String? { get }
}

class Promotion: PromotionProtocol {
    var promotionType: Int?
    var promotionCode: String?
    var fileName: String?
    var facetDescription: String?
    var promoDescription: String?
}

protocol PromotionInfoProtocol: Codable {
    var cornerPromotion: PromotionProtocol? { get }
    var mainPromotion: PromotionProtocol? { get }
    var isTopFive: Bool? { get }
}

class PromoInfo: PromotionInfoProtocol {
    var cornerPromotion: PromotionProtocol?
    var mainPromotion: PromotionProtocol?
    var isTopFive: Bool?
}

Everything inside the 'PromotionProtocol' is either a String or Int so that is fine. But I get the errors that the Class Promotion does not conform to Encodable and Decodable.

Hamish
  • 78,605
  • 19
  • 187
  • 280
SamRowley
  • 3,435
  • 7
  • 48
  • 77
  • 3
    `Promotion` *does* conforms to `Codable` – `PromoInfo` however doesn't. `PromotionProtocol` is not a type that conforms to `Codable` as protocols don't always conform to themselves (just think: what concrete type should be created on decoding `cornerPromotion` & `mainPromotion`?). Compare https://stackoverflow.com/q/44441223/2976878 – Hamish Oct 10 '17 at 12:27
  • 2
    Unrelated, but do all your properties *really* need to be optional? – Hamish Oct 10 '17 at 12:31
  • Possible duplicate of [Protocol extending Encodable (or Codable) does not conform to it](https://stackoverflow.com/questions/50346052/protocol-extending-encodable-or-codable-does-not-conform-to-it) – Shinforinpola Oct 17 '18 at 12:44

0 Answers0