【发布时间】: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特定属性,以防type是Pudding(不仅仅是Dish)。
标签: swift generics init codable