I have this class:
class Course<T: Dish> {
var amount: Int
var type: T
init(amount: Int, type: T) {
self.amount = amount
self.type = type
}
}
I don’t have access to Dish
. But let’s assume this implementation:
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)
}
I now want to encode/decode it to JSON like so:
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)
So I add Codable
conformity:
class Course<T: Dish>: Codable
As the functions for Codable
can’t be synthesized I get these error messages:
Type 'Course' does not conform to protocol 'Decodable'
Type 'Course' does not conform to protocol 'Encodable'
So, I need to write init and encode() myself.
Somewhere in the initializer I would decode the generic type T
.
How do I specify the type T
in the initializer to make it generic when there is no reference to that type in the function signature?
required init<T: Dish>(from decoder: Decoder) throws
The above results in this error message Generic parameter 'T' is not used in function signature
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…