swift - URLRequest 相等性不包括 httpBody

标签 swift urlrequest swift4.2

概览

有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/

相关文章:

基于 T 类型属性的通用结构的 Swift 扩展

objective-c - 在 @objc 协议(protocol)中用闭包定义方法

ios - 返回字符串数组并填充 UILabel - Swift 3

python - 在 Python 中检查图像 URL 是否指向真实图像

ios - 如何将数据数据从 Collection View 单元格传递到 View Controller

ios - Firebase云函数始终响应代码=-1001 "The request timed out."

swift - 如何使用其搜索结果快速更新 textField.text

ios - URLSession 结果为 NIL 数据

ios - 桥接 header 不存在。从 swift 3 转换到 swift 4.2 时出现错误

iOS Swift 到 Objective-C 如何将弱引用传递给数组?