繁体   English   中英

Swift-使用协议通过通用类型初始化类

[英]Swift - initialize class by generic type with protocol

我想调用这样的方法:

createModel(Model.Type, json)

函数应在参数中为给定类型调用构造函数。 构造函数在协议中定义(来自ObjectMapper)。 我不太熟悉快速的泛型类型。 这是我到目前为止所拥有的,但是没有用。

func createModel<T: Mappable>(model: T.Type, json: JSON){
    return model(JSON: json)
}

在这里,我已经在评论中对其进行了描述。 您的代码中有些情况是您交替使用JSON和JSON。 在代码中,我使用JSON来标识类型别名和json作为变量名。 Swift中的格式也是varName: type在参数列表中时varName: type

typealias JSON = [String: Any] // Assuming you have something like this

// Assuming you have this
protocol Mappable {
    init(json: JSON) // format = init(nameOfVariable: typeOfVariable)
}

class Model: Mappable {
    required init(json: JSON) {
        print("a") // actually initialize it here
    }
}

func createModel<T: Mappable>(model: T.Type, json: JSON) -> T {
    // Initializing from a meta-type (in this case T.Type that we int know) must explicitly use init. 
    return model.init(json: json) // the return type must be T also
}

// use .self to get the Model.Type
createModel(model: Model.self, json: ["text": 2])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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