我有两个列表的ui,两个列表中的单元格都是相同的。对于这两个ui,管理不同的Codable数组。即
FirstViewController包含firstdatamodel,SecondViewController包含seconddatamodel。
所以在FirstViewController中,在cellForRow方法中,我调用了代码:

func setPastCell(cell:WeekCell, data_dic:FirstDataModel) {
    cell.lblGoalA.text = predictScore1
    cell.lblGoalB.text = predictScore2
}

阵列:
struct FirstDataModel: Codable {
    var team1_name:String?
    var team2_name:String?
    var status:Int?
    var image:String?
    var score:Int?

}
struct SecondDataModel: Codable {
    var team1_name:String?
    var team2_name:String?
    var status:Int?
    var image:String?
    var count:Int?
    var balance:Int?
}

我想为firstdatamodel和seconddatamodel创建公共函数。那么我如何使用泛型函数来管理它呢?
如何在FirstDataModel中通过SecondDataModelsetPastCell(cell: WeekCell, data_dic: FirstDataModel)
提前谢谢!

最佳答案

具有共同性质的cratete协议

protocol DataModel {
    var team1_name:String? { get }
    var team2_name:String? { get }
    var status:Int? { get }
    var image:String? { get }

}

确认结构中的协议并添加其属性
struct FirstDataModel: DataModel, Codable {
    //Protocol properties
    var team1_name:String?
    var team2_name:String?
    var status:Int?
    var image:String?
    //additional properties
    var score:Int?
}
struct SecondDataModel: DataModel, Codable {
    //Protocol properties
    var team1_name:String?
    var team2_name:String?
    var status:Int?
    var image:String?
    //additional properties
    var count:Int?
    var balance:Int?
}

由于两个结构都符合数据模型协议,因此可以在函数参数中使用它。
func setPastCell<T: DataModel>(cell:WeekCell, data_dic:T) {

    if let firstModel = data_dic as? FirstDataModel {
        print(firstModel.team1_name)
        print(firstModel.team2_name)
        print(firstModel.status)
        print(firstModel.image)
        print(firstModel.score)
    } else if let secondModel = data_dic as? SecondDataModel {
        print(secondModel.team1_name)
        print(secondModel.team2_name)
        print(secondModel.status)
        print(secondModel.image)
        print(secondModel.count)
        print(secondModel.balance)
    }
}

09-26 08:17