如何在两个不同的键中使用相同的变量解码JSON?

时间:2018-12-10 10:26:54

标签: swift decodable

我正在学习let can_unify = function | TypeVar t1, TypeVar t2 when String.( = ) t1 t2 -> (* decide what to do here *) | TypeVar varname, t -> not (is_free ~varname t) | _ -> (* throw an error or fix your types so this case can’t happen *) 。这是我的模型:

Decodables

您可以在此处看到struct DQModel: Decodable{ var details: DQDetails } struct DQDetails: Decodable { var weekly_details: WeeklyDetails var your_turn: MyTurn var their_turn: TheirTurn } struct WeeklyDetails: Decodable { var win: Int? var loss: Int? } struct MyTurn: Decodable { var name: String? var pic: String? var current: String? var time: String? var win: Int? var loss: Int? } struct TheirTurn: Decodable { var name: String? var pic: String? var current: String? var time: String? var win: Int? var loss: Int? } MyTurn完全相同,但变量相同,但是它们只是不同的键。有什么方法可以让我不必再次重写TheirTurn?还是将来,如果有10到9个相同的情况出现,请问有什么方法可以减少复制/粘贴工作?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以为转弯创建一个通用的“结构”,并在两种情况下都使用它们(myTurn和themTurn)。您可以按照以下步骤进行操作:

struct Turn: Decodable {

var name: String?

var pic: String?

var current: String?

var time: String?

var win: Int?

var loss: Int?
}

并像这样使用它:

struct DQDetails: Decodable {

var weekly_details: WeeklyDetails

var your_turn: Turn

var their_turn: Turn

}

这将减少创建两个不同结构的工作量。