简体   繁体   中英

Swift - initialize class by generic type with protocol

i want to call a method like this:

createModel(Model.Type, json)

The function should call the constructor for the given type in the parameter. The constructor is defined in a protocol (from ObjectMapper). I am not that familiar with the generic types in swift. This is what I have so far but it doesn't work.

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

Here I have described it in the comments. There were some cases in your code were you were using JSON and json interchangeably. In the code I use JSON to identify the type alias and json as a variable name. Also the format in Swift is varName: type when in a parameter list

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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