Hi,
For HTTP requests, I have the following function:
func createAccount(account: Account, completion: @escaping (Response) -> Void) {
guard let url = URL(string: "http://localhost:4300/account") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
guard let encoded = try? JSONEncoder().encode(account) else {
print("Failed to encode request")
return
}
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let resData = try JSONDecoder().decode(Response, from: data)
DispatchQueue.main.async {
completion(resData)
}
} catch let jsonError as NSError {
print("JSON decode failed: \(jsonError)")
}
}.resume()
}
Because various HTTP requests use different body structs and response structs, I have a HTTP request function for each individual HTTP request. How can I condense this into one function, where the passed struct and return struct are varying, so I can perhaps pass the struct types in addition to the data to the function? Any guidance would be greatly appreciated.