使通用类可编码 [英] Make Generic Class Codable

查看:99
本文介绍了使通用类可编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这堂课:

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

我无权访问 Dish .但是,让我们假设此实现:

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)
}

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

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)

所以我添加了 Codable 一致性:

class Course<T: Dish>: Codable

由于无法合成 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'

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

So, I need to write init and encode() myself.

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

Somewhere in the initializer I would decode the generic type T.

当函数签名中没有对该类型的引用时,如何在初始化程序中指定类型 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

以上结果将导致此错误消息函数签名中未使用通用参数'T'.

The above results in this error message Generic parameter 'T' is not used in function signature.

推荐答案

就像上面其他人所说的那样,您还没有为这种通用性提供理由.但是,如果您能做到这一点,并且不能仅将Dish扩展为Codable,就可以对本地菜进行限制.并重命名它,因为"T"表示和类型"不精确.

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.

这篇关于使通用类可编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆