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"
...
}
headers是HTTPHeaders
類型遵岩,其實(shí)就是通過(guò)類型重命名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)換時(shí)出現(xiàn)錯(cuò)誤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
舉個(gè)官方的??后添,貌似挺好理解
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?的時(shí)候,我已經(jīng)知道這是個(gè)協(xié)議了蛙讥,而且有throws锯蛀,說(shuō)明我們?cè)趓eturn的時(shí)候需要try。
使用guard來(lái)判斷是否有值次慢,比if更加清晰
public protocol RequestAdapter {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}