ios - Swift - 使用协议(protocol)通过泛型类型初始化类

标签 ios json swift generics

我想调用这样的方法:

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/

相关文章:

objective-c - 使用 NSPredicate 搜索带数组的数组

ios - PhoneGap/Cordova + iOS7 + XCode 5

javascript - Nodejs json 字符串显示为 [object Object]

python - Flask jsonify 在新行打印结果

ios - 如何更改 CAShapeLayer alpha/opacity 值?

ios - 无法重新启用我的应用中的位置

ios - 如何在 watch 套件中显示通知,其中 iPhone 应用程序已经显示通知

json - 使用 Apps 脚本 API 创建新的 Apps 脚本文件 - 错误 - 收到无效的 JSON 负载

ios - 无法在 NSUserDefaults 中设置数组

ios - 向 UISearchController 添加过滤器按钮