我正在尝试编写一个通用的可重用 API 调用,它接受一个符合 Codable 协议的类型的参数。然后我打算将检索到的 JSON 解码为包含此通用参数类型的结构。我已将此结构命名为 NetworkResponse。
我对 Swift 比较陌生,所以非常感谢任何帮助!
// struct that will be used to decode JSON
struct NetworkResponse<T: Codable>: Codable {
var data : T?
var error: String
var msg: String
}
// Example struct that would be passed to the NetworkResponse struct above
struct AuthTokens: Codable, Hashable {
let access_token: String
let refresh_token: String
}
// My attempt at a generic reusable POST api call
func request<T: Codable>(
url: URL?,
body: [String: AnyHashable],
dataType: T.Type, // This argument would be the AuthTokens type (for example)
completion: @escaping(Result<T, Error>) -> Void
) -> Void {
guard let url = url else { return completion(.failure(APIError.invalidURL)) }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = ["Content-Type": "application/json"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
// Error: "Type of expression is ambiguous without more context"
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
guard let data = data else { return }
do {
// Error: "cannot find 'dataType' in scope"
let result = try JSONDecoder().decode(NetworkResponse<dataType>.self, from: data)
completion(.success(result))
}
catch { completion(.failure(APIError.parsingError)) }
}
task.resume()
}