Struct inherits codable and a protocol that has a property that is a protocol

79 Views Asked by At

I have a service that returns read-only data. In the service, I am modifying and saving the data and I have properties I want to hide outside the service. I want to expose only protocols in the interface of my service so that other developers can not create or modify these objects by mistake.

This is what it looks like

class MyService {
  func getData() -> [Protocol1]
}

protocol Protocol1 {
  var protocol2: Protocol2 { get }
}

protocol Protocol2 { }

struct Struct1: Protocol1, Codable {
  var id: String
  var lastModified: Date
  var protocol2: Struct2 // Error: Type 'Struct1' does not conform to protocol 'Protocol1'
}

struct Struct2: Protocol2, Codable { }

Am I out of luck? Am I going to need to just create a struct that is used outside the service and a struct for inside the service?

1

There are 1 best solutions below

0
Christophe On

To make your structure Struct1 comply to Protocol1, you can make protocol2 a computed property:

struct Struct1: Protocol1, Codable {
  var id: String
  var lastModified: Date
  var protocol2: Protocol2  { get { struct2 } }
  private var struct2: Struct2 
}