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 :
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:
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"):
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!
Selecting any option will automatically load the page