gpt4 book ai didi

swift - URLRequest 相等性不包括 httpBody

转载 作者:搜寻专家 更新时间:2023-10-31 22:04:18 26 4
gpt4 key购买 nike

概览

有2个URLRequest,一个有httpBody,一个没有httpBody
然而,当比较时,它表明两者是相等的。

问题

这是预期的行为还是我遗漏了什么?

代码

let url = URL(string: "www.somevalidURL.com")!

var r1 = URLRequest(url: url)
r1.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")
r1.httpBody = makeBody(withParameters: ["email" : "a@b.com"])

var r2 = URLRequest(url: url)
r2.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")

if r1 == r2 {
print("requests are equal")
}
else {
print("requests are not equal")
}

if r1.httpBody == r2.httpBody {
print("body is equal")
}
else {
print("body is not equal")
}

func makeBody(withParameters bodyParameters: [String : Any]?) -> Data? {
guard let bodyParameters = bodyParameters,
!bodyParameters.isEmpty else {
return nil
}
let body : Data?
do {
body = try JSONSerialization.data(withJSONObject: bodyParameters,
options: .prettyPrinted)
}
catch {
print("Error in creating Web Service Body = \(error)")
body = nil
}
return body
}

输出

requests are equal
body is not equal

<子>Xcode 10
swift 版本:4.2

最佳答案

URLRequest 是基础类型 NSURLRequest 的 Swift 覆盖类型,因此 == 最终调用 isEqual() 的方法NSURLRequest

Foundation 库是非 Apple 平台的开源,并且在 NSURLRequest.swift#L252我们发现:

open override func isEqual(_ object: Any?) -> Bool {
//On macOS this fields do not determine the result:
//allHTTPHeaderFields
//timeoutInterval
//httBody
//networkServiceType
//httpShouldUsePipelining
guard let other = object as? NSURLRequest else { return false }
return other === self
|| (other.url == self.url
&& other.mainDocumentURL == self.mainDocumentURL
&& other.httpMethod == self.httpMethod
&& other.cachePolicy == self.cachePolicy
&& other.httpBodyStream == self.httpBodyStream
&& other.allowsCellularAccess == self.allowsCellularAccess
&& other.httpShouldHandleCookies == self.httpShouldHandleCookies)

所以这似乎是故意的。

关于swift - URLRequest 相等性不包括 httpBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com