首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift通用URLRequest

Swift通用URLRequest
EN

Stack Overflow用户
提问于 2019-05-07 10:15:03
回答 1查看 190关注 0票数 0

我正在尝试创建一个可以在所有网络调用中重用的createRequest函数,其中一些需要发布JSON,而另一些则不需要,所以我在考虑创建一个接受可选泛型对象的函数;理论上是这样的:

代码语言:javascript
复制
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对象。我读到你不能这样做,除非你在返回函数上定义类型,但我不能在返回函数中定义我的对象。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-07 10:44:19

前言:这段代码是一堆不一致的缩进和不必要的空格(它读起来像一篇双倍行距的文章,哈哈),我把它清理干净了。

看起来你的函数需要一个T,但不是任何T,而是一个被约束为Encodable的any。这是一个常见的观察结果:更通用的泛型参数与更多的类型兼容,但我们可以使用它们做的更少。通过将T包含到Encodable,我们可以在JSONEncoder.encode中使用它。

标签withData:是一个用词不当的词,因为该参数没有类型Data。像withBody:这样的东西会工作得更好。

代码语言:javascript
复制
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")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56014636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档