文章40 | 阅读 19055 | 点赞0
class ModelLoader<T: Unboxable & Requestable> {
func load(completionHandler: (Result<T>) -> Void) {
networkService.loadData(from: T.requestURL) { data in
do {
try completionHandler(.success(unbox(data: data)))
} catch {
let error = ModelLoadingError.unboxingFailed(error)
completionHandler(.error(error))
}
}
}
}
protocol ModelLoading {
associatedtype Model
func load(completionHandler: (Result<Model>) -> Void)
}
class ViewController: UIViewController {
init(modelLoader: ModelLoading) {
...
}
}
Protocol 'ModelLoading' can only be used as a generic constraint because it as Self or associated type requirements
class ViewController: UIViewController {
init<T: ModelLoading>(modelLoader: T) where T.Model == MyModel {
...
}
}
class AnyModelLoader<T>: ModelLoading {
typealias CompletionHandler = (Result<T>) -> Void
private let loadingClosure: (CompletionHandler) -> Void
init<L: ModelLoading>(loader: L) where L.Model == T {
loadingClosure = loader.load
}
func load(completionHandler: CompletionHandler) {
loadingClosure(completionHandler)
}
}
class ViewController: UIViewController {
private let modelLoader: AnyModelLoader<MyModel>
init<T: ModelLoading>(modelLoader: T) where T.Model == MyModel {
self.modelLoader = AnyModelLoader(loader: modelLoader)
super.init(nibName: nil, bundle: nil)
}
}
class ViewController: UIViewController {
private let loadModel: ((Result<MyModel>) -> Void) -> Void
init<T: ModelLoading>(modelLoader: T) where T.Model == MyModel {
loadModel = modelLoader.load
super.init(nibName: nil, bundle: nil)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadModel { result in
switch result {
case .success(let model):
render(model)
case .error(let error):
render(error)
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Forever_wj/article/details/120957397
内容来源于网络,如有侵权,请联系作者删除!