如何使类中的公共属性成为通用属性

时间:2018-01-12 12:26:09

标签: ios swift generics

例如,我有4个模型类,其中包含3个名为name,value和amount的属性。如何创建一个接受我的模型类并相应工作的泛型类。每个类都有另一个类的对象。导致树状结构

Class A  {
//Its own properties
var name:String?
var value:Int?
var amounts:[Double?]
var listOfB:B?
}

Class B {
//Its own properties
var name:String?
var value:Int?
var amounts:[Double?]
var listOfC:C?
}

Class C {
//Its own properties
var name:String?
var value:Int?
var amounts:[Double?]
var listOfD:D?
}

Class D {
//Its own properties
var name:String?
var value:Int?
var amounts:[Double?]
}
到目前为止

代码

public class BaseModel<T: BaseModel> {
    public var avg : Double?
    public var id : String!
    public var subModels :[T]

    init(model: [T]) {
    }
}

class GenericModel<T: BaseModel > { // Model for all subclasses

 init(model: T) {
    if let a = model as? ListOfYears {
        model.avg = self.avg
        model.id = self.id
        model.subModel .init(model:self.subModels)
    }
    if let a = model as? listOfMonths {
        model.avg = self.avg
        model.id = self.id
        model.subModels.init(model:self.subModels)
    }
    if let a = model as? ListOfWeeks {
        model.avg = self.avg
        model.id = self.id
        model.subModels .init(model:ListOfYears.listOfMonths)
    }
}

这里ListOfYears,ListOfMonths,ListOfWeeks是我的模型类

1 个答案:

答案 0 :(得分:1)

当你真的不需要时,你试图强迫某些东西是通用的。正如@ user28434非常正确地指出的那样,一个优秀的老式超类在这里会做得很好。以下是您的案例示例:

class BaseModel {
    var name:String?
    var value:Int?
    var amounts:[Double]?
}

class A: BaseModel  {
    //Its own properties
}

class B: BaseModel {
    //Its own properties
}

class C: BaseModel {
    //Its own properties
}

class D: BaseModel {
    //Its own properties
}