Swift 3中的嵌套泛型 [英] nested generics in swift 3
问题描述
是否可以在Swift 3中使用泛型执行以下操作?
is it possible to do following in Swift 3 with generics ?
class BaseModel {}
class Human : BaseModel {
var name = ""
}
class BaseService<T: BaseVM<BaseModel>> {
//init viewmodel with generic model
}
class BaseVM<T: BaseModel> {}
class HumanVM: BaseVM<Human> {
var name = ""
init(model : Human) {
super.init()
name = model.name
}
}
class HumanService: BaseService<HumanVM> {}
我想做的是在baseService中使用通用模型初始化viewModel.
what I am trying to do is initializing viewModel with generic model in baseService.
推荐答案
是的,您可以嵌套泛型.您遇到的问题是此行:
Yes, you can nest generics. The problem with what you have is this line:
class BaseService<T: BaseVM<BaseModel>> { ...
在这里您已经说过BaseService
必须使用继承自BaseVM
的类型进行初始化,该类型的通用 IS BaseModel
.如果希望BaseService
能够采用从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> {}
描述这些关系的另一种方法是使用具有AssociatedTypes的协议.您的代码如下所示:
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.
编辑我仍然不太清楚这如何适用于MVVM模式,但是,如果涉及到视图,则可能需要基于Protocol
的解决方案,以便您可以使其符合UIView
.
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.
这篇关于Swift 3中的嵌套泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!