繁体   English   中英

Swift通用类如何从中创建类型对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM