Avatar
@swift-5.3.3 protocol EntityProtocol { associatedtype ID init(id: ID) } class Entity<ID>: EntityProtocol { let id: ID required init(id: ID) { self.id = id } enum CodingKeys: CodingKey { case id(String) var stringValue: String { switch self { case .id(let id): return id } } var intValue: Int? { nil } init?(stringValue: String) { self = .id(stringValue) } init?(intValue: Int) { return nil } } class func codingKeysForID() -> CodingKeys { .id("id") } } extension EntityProtocol where Self: Decodable, ID: Decodable { init(from decoder: Decoder) throws { let type = Self.self as! Entity<ID>.Type let c = try decoder.container(keyedBy: type.CodingKeys.self) self.init(id: try c.decode(ID.self, forKey: type.codingKeysForID())) } } (edited)