Alamofire.swift(三)-URLRequest

extension URLRequest {
    public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
        let url = try url.asURL()

        self.init(url: url)

        httpMethod = method.rawValue

        if let headers = headers {
            for (headerField, headerValue) in headers {
                setValue(headerValue, forHTTPHeaderField: headerField)
            }
        }
    }

    func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
        guard let adapter = adapter else { return self }
        return try adapter.adapt(self)
    }
}

url是繼承了URLConvertible協(xié)議的類型

method是HTTPMethod枚舉類型

public enum HTTPMethod: String {
case get = "GET"
case head = "HEAD"
case post = "POST"
...
}

headersHTTPHeaders類型,其實(shí)就是通過類型重命名typealias關(guān)鍵字,將key-value都為String類型的字典重命名為HTTPHeaders

//A dictionary of headers to apply to a URLRequest.
public typealias HTTPHeaders = [String: String]

并且可以看出,url和method都是必須要有的,headers是可選的


let url = try url.asURL()

這里用try,是因?yàn)閍sURL()定義在類型轉(zhuǎn)換時出現(xiàn)錯誤throws異常

self.init(url: url)

這里調(diào)用URLRequest的初始化方法
//Creates and initializes a URLRequest with the given URL and cache policy.
public init ( url: URL, cachePolicy: URLRequest.CachePolicy = default, timeoutInterval: TimeInterval = default )
這里的CachePolicy其實(shí)是NSURLRequest,默認(rèn)是:.useProtocolCachePolicy
public typealias CachePolicy = NSURLRequest.CachePolicy


httpMethod = method.rawValue

舉個官方的??,貌似挺好理解

enum PaperSize: String {
    case A4, A5, Letter, Legal
}
let selectedSize = PaperSize.Letter
print(selectedSize.rawValue)
// Prints "Letter"
print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
// Prints "true"

if let headers = headers {
            for (headerField, headerValue) in headers {
                setValue(headerValue, forHTTPHeaderField: headerField)
            }
        }

for循環(huán)的這種方式是由于headers是元組類型


當(dāng)看到using adapter: RequestAdapter?的時候,我已經(jīng)知道這是個協(xié)議了,而且有throws,說明我們在return的時候需要try。
使用guard來判斷是否有值,比if更加清晰

public protocol RequestAdapter {
    func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容