使通用类可编码

问题描述

我有这门课:

class Course<T: dish> {
    var amount: Int
    var type: T
    init(amount: Int,type: T) {
        self.amount = amount
        self.type = type
    }
}

我无权访问 dish。但让我们假设这个实现:

class dish {
    var calories: Double
    init(calories: Double) {
        self.calories = calories
    }
}

class Pudding: dish {
    static var iceCream = dish(calories: 400)
    static var chocoloteMousse = dish(calories: 600)
}

我现在想像这样将它编码/解码为 JSON:

import Foundation
var course = Course(amount: 1,type: Pudding.iceCream)
var encoded = try JSONEncoder().encode(course)
var decoded = try JSONDecoder().decode(Course.self,from: encoded)

所以我添加Codable 一致性:

class Course<T: dish>: Codable

由于 Codable函数无法合成,我收到以下错误消息:

Type 'Course' does not conform to protocol 'Decodable'
Type 'Course' does not conform to protocol 'encodable'

所以,我需要自己编写 init 和 encode()。

在初始化程序的某个地方,我会解码泛型类型 T

函数签名中没有对该类型的引用时,如何在初始化程序中指定类型 T 以使其通用?

required init<T: dish>(from decoder: Decoder) throws

以上导致此错误消息 Generic parameter 'T' is not used in function signature

解决方法

就像上面其他人所说的那样,您还没有证明它必须是通用的。但是如果你能做到这一点,并且你不能只是将 Dish 扩展为 Codable,只需对本地菜进行限制。并重命名它,因为“T”和“类型”是不精确的。

class Course<Dish: ModuleName.Dish & Codable>: Codable {
  var amount: Int
  var dish: Dish

你能做的最好的事情就是禁止子类化。永远,在你自己的所有类型中。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...