use*_*037 3 urlrequest swift swift4.2
有2 URLRequests,一个有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
}
Run Code Online (Sandbox Code Playgroud)
requests are equal
body is not equal
Run Code Online (Sandbox Code Playgroud)
Xcode 10
Swift版本:4.2
URLRequest是Foundation类型的Swift覆盖类型NSURLRequest,因此==最终调用的isEqual()方法NSURLRequest。
Foundation库是非Apple平台的开放源代码,在 NSURLRequest.swift#L245中,我们发现:
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)
Run Code Online (Sandbox Code Playgroud)
因此,这似乎是故意的。
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |