[英]Swift generic class how to create a type object from it
我有一個通用類,它應該簡單地將一個模型映射到一個視圖模型(和其他東西,但主要是這個)。
class InfoProv <M, VM: CreationableFromModel> {
var models = [M]()
var viewModels = [VM]()
func generateModelView() -> VM {
return VM(model: M)
}
}
protocol CreationableFromModel {
typealias Model
init(model: Model)
}
與協議CreationableFromModel
的一致性表明,視圖模型必須知道如何使用Model類型創建自身。
我真的不明白如何使傳遞給VM初始化的Model有效實例
您的代碼中只有小問題
protocol CreationableFromModel {
typealias Model
init(model: Model)
}
// you need a generic constraint to create a connection between the two generic types
class InfoProv <M, VM: CreationableFromModel where VM.Model == M> {
var models = [M]()
var viewModels = [VM]()
func generateModelView(m: M) -> VM {
// you were passing type M here, you need an instance m of type M
return VM(model: m)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.