【问题标题】:Make Generic Class Codable使泛型类可编码
【发布时间】:2021-04-21 06:25:43
【问题描述】:

我有这门课:

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

【问题讨论】:

  • 我不知道你为什么要在这里使用泛型;除非有更广泛的背景,否则它似乎没有意义。只需将 Course 的 type 属性设为 Dish 类型即可?
  • 你说你无法访问 Dish,但你知道这个类有什么属性吗?
  • @JoakimDanielson 是的
  • 慕斯并不是真正的布丁。冰淇淋绝对不是布丁。
  • @flanker 无法将课程的类型属性设为 Dish 类型。我想访问Pudding 特定属性,以防typePudding(不仅仅是Dish)。

标签: swift generics init codable


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答。 “本地菜”是什么意思?
  • 您的命名不准确。你的type / T 实际上是一个专门的Dish。通过使用可怕的约定T(该约定是很久以前的行业,而不是您的约定。我没有因此而责备您。),这并没有使自己足够明显。它实际上是一个Course.Dish,它是您模块中Dish 的改进。在模块范围的Dish 前面加上模块名称(上面的ModuleName.Dish)以消除歧义。那么Dish,当在Course 中使用时,将是locally-scoped ——“本地菜肴”。
猜你喜欢
  • 1970-01-01
  • 2018-10-05
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 2021-10-22
  • 1970-01-01
相关资源
最近更新 更多