如何将现有封装的get请求方法适配应用到其他Model模型中
你可以通过泛型+参数化配置的方式改造现有方法,让它支持任意遵守Decodable协议的模型类型,同时将请求URL等可变配置提取为入参,即可适配不同的网络请求场景。
核心改造点
- 给方法添加遵守
Decodable协议的泛型约束,替换硬编码的固定Model类型 - 将请求URL、解析目标类型提取为方法入参,避免内部硬编码
- 优化错误处理逻辑,避免吞掉解析异常,方便问题排查
改造后代码示例
class Network { /// 通用GET请求方法 /// - Parameters: /// - urlString: 请求地址字符串 /// - type: 解析目标模型类型 /// - completion: 请求完成回调,返回可选的解析结果 func getData<T: Decodable>(urlString: String, type: T.Type, completion : @escaping (T?) -> ()) async { guard let url = URL(string: urlString) else { completion(nil) return } do { let (data, _) = try await URLSession.shared.data(from: url) let decodedResult = try JSONDecoder().decode(T.self, from: data) completion(decodedResult) } catch { print("请求/解析错误: \(error.localizedDescription)") completion(nil) } } }
使用示例
原有Model场景调用
let network = Network() Task { await network.getData( urlString: "https://jsonplaceholder.typicode.com/posts", type: [Model].self ) { posts in guard let posts = posts else { return } // 原有业务逻辑处理 } }
其他自定义Model场景调用
// 自定义新的User模型,只要遵守Decodable协议即可 struct User: Decodable { let id: Int let name: String let email: String } // 新场景调用 Task { await network.getData( urlString: "https://jsonplaceholder.typicode.com/users", type: [User].self ) { users in guard let users = users else { return } // 新场景业务逻辑处理 } }
可选优化方案
如果需要更灵活的错误处理,可以将回调修改为返回Result类型,把错误信息透传给调用层:
func getData<T: Decodable>(urlString: String, type: T.Type, completion : @escaping (Result<T, Error>) -> ()) async { guard let url = URL(string: urlString) else { completion(.failure(NSError(domain: "Network", code: -1, userInfo: [NSLocalizedDescriptionKey: "无效URL"]))) return } do { let (data, _) = try await URLSession.shared.data(from: url) let decodedResult = try JSONDecoder().decode(T.self, from: data) completion(.success(decodedResult)) } catch { completion(.failure(error)) } }
内容的提问来源于stack exchange,提问作者A D Arman Akash
相关产品推荐
相关产品推荐

