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

我正在学习 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?
}

你可以在这里看到 MyTurnTheirTurn 与相同的变量完全相同,但它们只是不同的键 . 有什么方法我不必再次重写 variables 吗?或者将来,如果有任何案例像10个,9个相同,是否有任何方法可以遵循以减少复制/粘贴工作?

提前致谢 .

回答(1)

2 years ago

您可以为转弯创建一个通用的“结构”,并在两种情况下使用它们(myTurn&theirTurn) . 你可以这样做:

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

}

它将减少您创建两个不同结构的工作量 .