我想编写一个通用函数,该函数解析结果并在闭包的成功块中返回,或在失败块中发回错误。
我遇到类似“无法推断出通用参数'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)
}
}
这是我遇到的错误。
您可以接受通用类型作为参数,如下所示:
func fetchObject<T:Decodable>(ofType type: T.Type, _ completion: @escaping (Result<T, PostError>) -> Void) {
do {
let data = Data(jsonString.utf8)
let post = try JSONDecoder().decode(type, from: data)
completion(.success(post))
}
catch {
completion(.failure(.empty))
}
}
用法:
fetchObject(ofType: Post.self) { res in
switch res {
case .success(let post):
print(post.description)
case .failure(let error):
print(error)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句