Ste*_*ann 1 generics json ios swift
我想调用这样的方法:
createModel(Model.Type, json)
Run Code Online (Sandbox Code Playgroud)
该函数应调用参数中给定类型的构造函数。构造函数在协议中定义(来自 ObjectMapper)。我对 swift 中的泛型类型不太熟悉。这是我到目前为止所拥有的,但它不起作用。
func createModel<T: Mappable>(model: T.Type, json: JSON){
return model(JSON: json)
}
Run Code Online (Sandbox Code Playgroud)
在这里,我在评论中对其进行了描述。您的代码中有一些情况是您交替使用 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])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2317 次 |
| 最近记录: |