【发布时间】:2020-06-17 22:53:47
【问题描述】:
我想编写一个通用函数来解析结果并在闭包的成功块中返回或在失败块中发送回错误。
我遇到了这样的错误'无法推断通用参数'T''。
这是我的示例代码。
let jsonString = """
{
"id": 1,
"msg": "Sample msg"
}
"""
struct Post: Codable {
var id: String?
var msg: String?
}
enum PostError: Error {
case empty
}
func fetch<T:Decodable>(_ completion: @escaping (Result<T?, PostError>) -> Void) {
do {
let data = Data(jsonString.utf8)
let post = try JSONDecoder().decode(T.self, from: data)
completion(.success(post))
}
catch {
completion(.failure(.empty))
}
}
fetch { res in
switch res {
case .success( let p):
print(p.description)
case .failure(let error):
print(error)
}
}
这是我遇到的错误。
【问题讨论】:
-
我猜你希望
res成为Result<Post?, PostError>?但是Post?没有description属性。