Ios Swift-使用协议按泛型类型初始化类

Ios Swift-使用协议按泛型类型初始化类,ios,json,swift,generics,Ios,Json,Swift,Generics,我想调用如下方法: createModel(Model.Type, json) 函数应该调用参数中给定类型的构造函数。构造函数是在ObjectMapper的协议中定义的。我不太熟悉swift中的泛型类型。这是我到目前为止所做的,但它不起作用 func createModel<T: Mappable>(model: T.Type, json: JSON){ return model(JSON: json) } 在这里,我已经在评论中对此进行了描述。在您的代码中,有一些情况是

我想调用如下方法:

createModel(Model.Type, json)
函数应该调用参数中给定类型的构造函数。构造函数是在ObjectMapper的协议中定义的。我不太熟悉swift中的泛型类型。这是我到目前为止所做的,但它不起作用

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

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

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

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

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

您缺少返回类型,即,将->T添加到函数中。您缺少返回类型,即,将->T添加到函数中。工作起来很有魅力。谢谢你,这工作很有魅力。非常感谢。