Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

swift - Make Generic Class Codable

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like others have said above, you haven't made a case for this having to be generic yet. But if you can make that case, and you can't just extend Dish to be Codable, just put a restriction on the local dish. And rename it, because "T" and "type" are imprecise.

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

The best thing you can do to make this easier on yourself is to forbid subclassing. Forever, in all of your own types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...