[英]iOS Generic swift closure
I want to Pass a generic model object in swift. 我想快速传递通用模型对象。
Currently I have a closure that have to return the Model object as below 目前,我有一个必须返回Model对象的闭包,如下所示
completionHandler = ([ModelObject]?, Error?) -> Void
Method calling 方法调用
func method1( onCompletion: @escaping completionHandler) -> Void {
}
I want to make a generic completionhandler that can pass different model instead of specific Model. 我想制作一个可以通过不同模型而不是特定模型的通用完成处理程序。 Note:- all model object conform to Codable protocol as below
注意:-所有模型对象均符合以下Codable协议
struct ModelObject: Codable {
}
//===== Edit====== // =====编辑======
func method1<M: Codable>( onCompletion: @escaping (M?, Error?) -> Void) -> Void {
let decoder = JSONDecoder()
let items = try? decoder.decode(ModelObject.self, from: data)
onCompletion(items, nil)// error in this line Cannot convert value of type 'ModelObject?' to expected argument type '_?'
}
You can create your method something like: 您可以创建类似于以下内容的方法:
func method1<Model: Codable>(onCompletion: @escaping (Model?, Error?) -> Void) -> Void {
let decoder = JSONDecoder()
let itemObj = try? decoder.decode(Model.self, from: data)
onCompletion(itemObj, nil)
}
And if you have your struct like: 如果您的结构像:
struct ModelObject: Codable {
}
you can call this method like: 您可以像这样调用此方法:
method1 { (model: ModelObject?, error) in
}
You have another struct like: 您还有另一个结构,例如:
struct AnotherModelObject: Codable {
}
You can call it like: 您可以这样称呼它:
method1 { (model: AnotherModelObject?, error) in
}
You can hide the protocol inside another struct or you can use a custom container. 您可以将协议隐藏在另一个结构中,也可以使用自定义容器。
protocol Container { }
struct Storage {
let model: Codable
}
struct ModelObject: Codable, Container {
}
enum Result<T> {
case data(result: T)
}
typealias completionHandler = ([Storage]?, Error?) -> Void
func method1(onCompletion: @escaping completionHandler) -> Void {
onCompletion([Storage(model:ModelObject())], nil)
}
func method2(onCompletion: @escaping ([Result<Codable>]) -> Void) -> Void {
onCompletion([Result.data(result: ModelObject() as Codable)])
}
method1 { result, _ in
print(result![0].model)
}
method2 { result in
print(result[0])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.