1

Below code compiles fine (Swift 5.0+)

import Foundation

protocol PriceType: Codable {
    var value: Double {get set}
    var currency: String {get set}
}

struct Price: PriceType {
    var value: Double
    var currency: String
}

struct Quantity: Codable {
    var value: Double
    var unit : String
}

struct Commodity: Codable {
    var price: Price
    var quantity: Quantity
}

The moment I change the definition of Commodity to below, the code doesn't compile.

struct Commodity: Codable {
    var price: PriceType
    var quantity: Quantity
}

The only change I made is that I made price property of the type PriceType.

I get below error

error: 019 - Codeable v2.xcplaygroundpage:20:8: error: type 'Commodity' does not conform to protocol 'Decodable' struct Commodity: Codable { ^

019 - Codeable v2.xcplaygroundpage:21:9: note: cannot automatically synthesize 'Decodable' because 'PriceType' does not conform to 'Decodable' var price: PriceType ^

error: 019 - Codeable v2.xcplaygroundpage:20:8: error: type 'Commodity' does not conform to protocol 'Encodable' struct Commodity: Codable { ^

019 - Codeable v2.xcplaygroundpage:21:9: note: cannot automatically synthesize 'Encodable' because 'PriceType' does not conform to 'Encodable' var price: PriceType

As per Apple Documentation

The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, and Double; and Foundation types like Date, Data, and URL. Any type whose properties are codable automatically conforms to Codable just by declaring that conformance.

Since PriceType conform to Codable as its two properties i.e. value and currency are by default Codable then why code fails to compile if I made the price property of type PriceType (protocol) instead of Price (struct)??

Ishwar Jindal
  • 373
  • 1
  • 2
  • 10

1 Answers1

0

Protocols do not conform to themselfs or protocols they inherit, see: Protocol extending Encodable (or Codable) does not conform to it. This won't be fixed, see: https://bugs.swift.org/browse/SR-5853?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel

I think what you actually want is something like this:

struct Commodity<T: PriceType>: Codable {
    var price: T
    var quantity: Quantity
}
J. Doe
  • 12,159
  • 9
  • 60
  • 114