我正在尝试创建一个可以在所有网络调用中重用的createRequest函数,其中一些需要发布JSON,而另一些则不需要,所以我在考虑创建一个接受可选泛型对象的函数;理论上是这样的:
struct Person: Codable {
var fName: String
var lName: String
}
struct Location: Codable {
var city: String
var state: String
}
let data = Person(fName: "John", lName: "Smith")
let location = Location(city: "Atlanta", state: "Georgia")
createRequest(withData: data)
createRequest(withData: location)
private func createRequest(withData:T) throws -> URLRequest {
var newRequest = URLRequest(url: URL(string: "\(withUrl)")!)
newRequest.httpMethod = method.rawValue
if let data = withData {
newRequest.setBody = data
}
if withAPIKey {
newRequest.setValue(apiKey, forHTTPHeaderField: "APIKEY")
}
return newRequest
}我想返回URLRequest,并允许此函数传递不同的JSON对象。我读到你不能这样做,除非你在返回函数上定义类型,但我不能在返回函数中定义我的对象。
发布于 2019-05-07 10:44:19
前言:这段代码是一堆不一致的缩进和不必要的空格(它读起来像一篇双倍行距的文章,哈哈),我把它清理干净了。
看起来你的函数需要一个T,但不是任何T,而是一个被约束为Encodable的any。这是一个常见的观察结果:更通用的泛型参数与更多的类型兼容,但我们可以使用它们做的更少。通过将T包含到Encodable,我们可以在JSONEncoder.encode中使用它。
标签withData:是一个用词不当的词,因为该参数没有类型Data。像withBody:这样的东西会工作得更好。
import Foundation
struct Person: Codable {
var fName: String
var lName: String
}
struct Location: Codable {
var city: String
var state: String
}
// stubs for making compilation succeed
let apiKey = "dummy"
let withAPIKey = true
enum HTTPMethod: String { case GET }
private func createRequest<Body: Encodable>(method: HTTPMethod, url: URL, withBody body: Body) throws -> URLRequest {
var newRequest = URLRequest(url: url)
newRequest.httpMethod = method.rawValue
newRequest.httpBody = try JSONEncoder().encode(body)
if withAPIKey {
newRequest.setValue(apiKey, forHTTPHeaderField: "APIKEY")
}
return newRequest
}
let data = Person(fName: "John", lName: "Smith")
let location = Location(city: "Atlanta", state: "Georgia")https://stackoverflow.com/questions/56014636
复制相似问题