swift - Local and Network Data Manager
问题描述
I'm facing a strange issue i'm not able to track down.
I have a DataManager that is responsable to return data to my TableViewController.
This is the code
typealias NewsListCompletionBlock = (Result<NewsList>) -> Void
class DataManager {
var subManager: DataManagerProtocol
init() {
if (Config.isUITests()) {
subManager = LocalDataManager()
} else {
subManager = NetworkDataManager()
}
}
}
// MARK: News data manager
extension DataManager {
func getNewsList(completion:@escaping NewsListCompletionBlock) {
subManager.performRequest(route: nil, decoder: JSONDecoder(),
completion: completion)
}
}
This initializes a subManager based on if we are running UITests or we are running the real application.
Real application works as expected, but the LocalDataManager returns an error i can't track down.
class LocalDataManager: DataManagerProtocol {
@discardableResult
func performRequest<T>(route: APIRouter?, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T>) -> Void) -> DataRequest where T : Decodable {
let newsListString = """
{
"news" : [
{
"id": 262,
"category": "e",
"title": "Scott Johnson & Paul Fowler Workshop",
"subtitle": "Wedding Photography Workshop | 20th-24th May 2019, Italy",
"link": "",
"date": "2018-08-31"
}
]
}
"""
if let jsonData = newsListString.data(using: .utf8)
{
let result :Result<NewsList>
do {
let newsListObject = try JSONDecoder().decode(NewsList.self, from: jsonData)
result = Result.success(newsListObject)
} catch {
result = Result.failure(NSError(domain: "", code: 123, userInfo: nil))
}
completion(result)
}
}
}
This is the code of the LocalDataManager. As you can see i simulate the call of the completion block providing dummy data, but when i compile i get
DataManager/LocalDataManager.swift:38:24: Cannot convert value of type 'Result<NewsList>' to expected argument type 'Result<_>'
解决方案
这是因为您使用NewsList
显式代替泛型参数。
将代码更改为以下将起作用。
if let jsonData = newsListString.data(using: .utf8)
{
let result :Result<T>
do {
let newsListObject = try JSONDecoder().decode(T.self, from: jsonData)
result = Result.success(newsListObject)
} catch {
result = Result.failure(NSError(domain: "", code: 123, userInfo: nil))
}
completion(result)
}
推荐阅读
- laravel - 如何在主模型删除的数据库事务中包含 Laravel 模型启动“删除”方法?
- python - 如何每 5 秒连续收集数据并保存到文件
- python - Array 上的算术运算导致 TypeError: unsupported operand type(s) for -: 'str' and 'str'
- java - Jfrog Artifactory OSS 优于 Bitnami Jfrog Artifactory
- r - 如何在for循环中使用grep函数
- python - 如何解析日志文本文件、解析日期时间并获取时间增量总和
- python - VSCode 移动到另一个工作站时使用错误的 python 路径
- sql - 从每个区域中选择前 3 条记录
- javascript - 如何检测 JSON 日期字符串?
- shell - 使用补丁/差异从文件恢复到原始文件之一