簡體   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