Yes, you can nest generics. The problem with what you have is this line:
class BaseService<T: BaseVM<BaseModel>> { ...
Here you've said BaseService must be initialized with a type that inherits from BaseVM whose generic IS BaseModel. If you want BaseService to be able to take a type that inherits from BaseVM whose model inherits from BaseModel, you'd have to do it this way:
class BaseService<T: BaseModel, U: BaseVM<T>> { ...
Here is a version of what you have above that compiles:
class BaseModel {}
class BaseVM<T: BaseModel> {}
class BaseService<T: BaseModel, U: BaseVM<T>> {
//init viewmodel with generic model
}
class Human : BaseModel {
var name = ""
}
class HumanVM: BaseVM<Human> {
var name = ""
init(model : Human) {
super.init()
name = model.name
}
}
class HumanService: BaseService<Human, HumanVM> {}
An alternate approach to describing these relationships would be to use Protocols with AssociatedTypes. Your code would look something like this:
protocol Model {}
protocol BaseVM {
associatedtype VMModel : Model
}
protocol BaseService {
associatedtype ServiceVM : BaseVM
}
class Human : Model {
var name = ""
}
class HumanVM : BaseVM {
typealias VMModel = Human
}
class HumanService : BaseService {
typealias ServiceVM = HumanVM
}
Without knowing more about what problem you're trying to solve, I can't say which is more appropriate.
EDIT I'm still not totally clear how this is applicable to the MVVM pattern, but probably, if views are involved, you'd want a Protocol-based solution so that you could make UIView conform to it.
评论
发表评论