Swift complaining non-conformance to Encodable on protocol while Encodable is conformed

Dear Developers,

I've written a struct which conforms to Encodable. To make this work, the type of every property should also be Encodable. In this struct, named "Message", I have a custom type (which is a protocol named "TelegramId") that has already conformed to Encodable and also offered a default implementation of encode(to encoder: Encoder) through extension, however, when I am trying to build the code, the compiler said that "Message" doesn't conform to Encodable because "TelegramId" doesn't conform to Encodable, which it actually has conformed to, so I wonder how I can get rid of this error?

Code & Error Message

Code:

struct Message :
Code Block swift
struct Message: Encodable {
  let chatId: TelegramId
  let text: String
  let mode: String = "MarkdownV2"
  let mute: Bool
  enum CodingKeys: String, CodingKey {
   case chatId = "chat_id"
   case text
   case mode = "parse_mode"
   case mute = "disable_notification"
  }
  init(to chat: TelegramId, content: String, mute: Bool) {
   self.chatId = chat
   self.text = content
   self.mute = mute
  }
 }


protocol TelegramId:
Code Block swift
public protocol TelegramId: Encodable {
 var rawId: TelegramRawId { get }
 init(_: TelegramRawId)
}
extension TelegramId {
 public static func id(_ id: Int) -> Self {
  return Self(.id(id))
 }
 public static func name(_ name: String) -> Self {
  return Self(.name(name))
 }
 public func encode(to encoder: Encoder) throws {
  var container = encoder.singleValueContainer()
  try container.encode(self.rawId)
 }
}


enum TelegramRawId (the type of the property "rawId" in "TelegramId"):
Code Block swift
public enum TelegramRawId: Encodable {
 case id(Int)
 case name(String)
 public func encode(to encoder: Encoder) throws {
  var container = encoder.singleValueContainer()
  switch self {
  case .id(let userId):
   try container.encode(userId)
  case .name(let userName):
   try container.encode("@" + userName)
  }
 }
}

error message:


Type 'Message' does not conform to protocol 'Encodable'

Cannot automatically synthesize 'Encodable' because 'TelegramId' does not conform to 'Encodable'

Thank you so much for your time to view my question and answer it!

Unfortunately, in Swift, even if you declare a protocol inheriting some other protocol, the protocol you declared does not conform to the other protocol.

In your case, your protocol TelegramId does inherit Encodable, but does NOT conform to Encodable.
You need to specify a type conforming to Encodable, but your TelegramId does not.

You may need to implement encode(to:) of Message by yourself.
Or else you need to use some other type conforming to Encodable.


@OOPer Can you give please more detailed answer, with example from original code

Swift complaining non-conformance to Encodable on protocol while Encodable is conformed
 
 
Q