我想调用这样的方法:
createModel(Model.Type, json)
函数应该调用参数中给定类型的构造函数。构造函数在协议(protocol)中定义(来自 ObjectMapper)。我不太熟悉 swift 中的泛型类型。这是我目前所拥有的,但它不起作用。
func createModel<T: Mappable>(model: T.Type, json: JSON){
return model(JSON: json)
}
最佳答案
这里我已经在评论里描述过了。在您的代码中有一些情况是您交替使用 JSON 和 json。在代码中,我使用 JSON 来标识类型别名,并使用 json 作为变量名。在参数列表中,Swift 中的格式也是 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])
关于ios - Swift - 使用协议(protocol)通过泛型类型初始化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43033065/