Browse Source

Audited logic for multiple if let binding and formatting...no functional changes.

Christian Noon 10 years ago
parent
commit
338955a547

+ 2 - 0
Source/Download.swift

@@ -43,11 +43,13 @@ extension Manager {
         }
         }
 
 
         let request = Request(session: self.session, task: downloadTask)
         let request = Request(session: self.session, task: downloadTask)
+
         if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
         if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
             downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
             downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
                 return destination(URL, downloadTask.response as! NSHTTPURLResponse)
                 return destination(URL, downloadTask.response as! NSHTTPURLResponse)
             }
             }
         }
         }
+
         self.delegate[request.delegate.task] = request.delegate
         self.delegate[request.delegate.task] = request.delegate
 
 
         if self.startRequestsImmediately {
         if self.startRequestsImmediately {

+ 2 - 2
Source/Manager.swift

@@ -72,8 +72,9 @@ public class Manager {
 
 
                 var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
                 var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
                 let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
                 let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
+
                 if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
                 if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
-                    return mutableUserAgent as NSString as! String
+                    return mutableUserAgent as String
                 }
                 }
             }
             }
 
 
@@ -291,7 +292,6 @@ public class Manager {
                 taskDidComplete(session, task, error)
                 taskDidComplete(session, task, error)
             } else if let delegate = self[task] {
             } else if let delegate = self[task] {
                 delegate.URLSession(session, task: task, didCompleteWithError: error)
                 delegate.URLSession(session, task: task, didCompleteWithError: error)
-
                 self[task] = nil
                 self[task] = nil
             }
             }
         }
         }

+ 2 - 2
Source/ParameterEncoding.swift

@@ -103,8 +103,7 @@ public enum ParameterEncoding {
                 }
                 }
             }
             }
 
 
-            let method = Method(rawValue: mutableURLRequest.HTTPMethod)
-            if let method = method where encodesParametersInURL(method) {
+            if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
                 if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
                 if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
                     URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!)
                     URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!)
                     mutableURLRequest.URL = URLComponents.URL
                     mutableURLRequest.URL = URLComponents.URL
@@ -118,6 +117,7 @@ public enum ParameterEncoding {
             }
             }
         case .JSON:
         case .JSON:
             let options = NSJSONWritingOptions.allZeros
             let options = NSJSONWritingOptions.allZeros
+
             if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
             if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
                 mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
                 mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
                 mutableURLRequest.HTTPBody = data
                 mutableURLRequest.HTTPBody = data

+ 12 - 4
Source/Request.swift

@@ -403,6 +403,7 @@ extension Request: Printable {
     /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
     /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
     public var description: String {
     public var description: String {
         var components: [String] = []
         var components: [String] = []
+
         if let HTTPMethod = self.request.HTTPMethod {
         if let HTTPMethod = self.request.HTTPMethod {
             components.append(HTTPMethod)
             components.append(HTTPMethod)
         }
         }
@@ -430,7 +431,14 @@ extension Request: DebugPrintable {
         }
         }
 
 
         if let credentialStorage = self.session.configuration.URLCredentialStorage {
         if let credentialStorage = self.session.configuration.URLCredentialStorage {
-            let protectionSpace = NSURLProtectionSpace(host: URL!.host!, port: URL!.port?.integerValue ?? 0, `protocol`: URL!.scheme!, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
+            let protectionSpace = NSURLProtectionSpace(
+                host: URL!.host!,
+                port: URL!.port?.integerValue ?? 0,
+                `protocol`: URL!.scheme!,
+                realm: URL!.host!,
+                authenticationMethod: NSURLAuthenticationMethodHTTPBasic
+            )
+
             if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
             if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
                 for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
                 for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
                     components.append("-u \(credential.user!):\(credential.password!)")
                     components.append("-u \(credential.user!):\(credential.password!)")
@@ -446,9 +454,9 @@ extension Request: DebugPrintable {
         // See https://github.com/CocoaPods/swift/issues/24
         // See https://github.com/CocoaPods/swift/issues/24
         #if !os(OSX)
         #if !os(OSX)
             if self.session.configuration.HTTPShouldSetCookies {
             if self.session.configuration.HTTPShouldSetCookies {
-                if let cookieStorage = self.session.configuration.HTTPCookieStorage,
-                    cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
-                    where !cookies.isEmpty
+                if let
+                    cookieStorage = self.session.configuration.HTTPCookieStorage,
+                    cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie] where !cookies.isEmpty
                 {
                 {
                     let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
                     let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
                     components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
                     components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")

+ 8 - 10
Source/ResponseSerialization.swift

@@ -38,10 +38,8 @@ extension Request {
                 return (nil, nil)
                 return (nil, nil)
             }
             }
 
 
-            if encoding == nil {
-                if let encodingName = response?.textEncodingName {
-                    encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
-                }
+            if let encodingName = response?.textEncodingName where encoding == nil {
+                encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
             }
             }
 
 
             let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding)
             let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding)
@@ -59,9 +57,9 @@ extension Request {
         :returns: The request.
         :returns: The request.
     */
     */
     public func responseString(encoding: NSStringEncoding? = nil, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self  {
     public func responseString(encoding: NSStringEncoding? = nil, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self  {
-        return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
+        return response(serializer: Request.stringResponseSerializer(encoding: encoding)) { request, response, string, error in
             completionHandler(request, response, string as? String, error)
             completionHandler(request, response, string as? String, error)
-        })
+        }
     }
     }
 }
 }
 
 
@@ -97,9 +95,9 @@ extension Request {
         :returns: The request.
         :returns: The request.
     */
     */
     public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
     public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
-        return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { request, response, JSON, error in
+        return response(serializer: Request.JSONResponseSerializer(options: options)) { request, response, JSON, error in
             completionHandler(request, response, JSON, error)
             completionHandler(request, response, JSON, error)
-        })
+        }
     }
     }
 }
 }
 
 
@@ -135,8 +133,8 @@ extension Request {
         :returns: The request.
         :returns: The request.
     */
     */
     public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
     public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
-        return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { request, response, plist, error in
+        return response(serializer: Request.propertyListResponseSerializer(options: options)) { request, response, plist, error in
             completionHandler(request, response, plist, error)
             completionHandler(request, response, plist, error)
-        })
+        }
     }
     }
 }
 }

+ 5 - 0
Source/Upload.swift

@@ -46,15 +46,18 @@ extension Manager {
             dispatch_sync(self.queue) {
             dispatch_sync(self.queue) {
                 uploadTask = self.session.uploadTaskWithStreamedRequest(request)
                 uploadTask = self.session.uploadTaskWithStreamedRequest(request)
             }
             }
+
             HTTPBodyStream = stream
             HTTPBodyStream = stream
         }
         }
 
 
         let request = Request(session: self.session, task: uploadTask)
         let request = Request(session: self.session, task: uploadTask)
+
         if HTTPBodyStream != nil {
         if HTTPBodyStream != nil {
             request.delegate.taskNeedNewBodyStream = { _, _ in
             request.delegate.taskNeedNewBodyStream = { _, _ in
                 return HTTPBodyStream
                 return HTTPBodyStream
             }
             }
         }
         }
+
         self.delegate[request.delegate.task] = request.delegate
         self.delegate[request.delegate.task] = request.delegate
 
 
         if self.startRequestsImmediately {
         if self.startRequestsImmediately {
@@ -127,6 +130,7 @@ extension Manager {
     */
     */
     public func upload(method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request {
     public func upload(method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request {
         let mutableURLRequest = URLRequest(method, URLString, headers: headers)
         let mutableURLRequest = URLRequest(method, URLString, headers: headers)
+
         return upload(mutableURLRequest, data: data)
         return upload(mutableURLRequest, data: data)
     }
     }
 
 
@@ -160,6 +164,7 @@ extension Manager {
     */
     */
     public func upload(method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request {
     public func upload(method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request {
         let mutableURLRequest = URLRequest(method, URLString, headers: headers)
         let mutableURLRequest = URLRequest(method, URLString, headers: headers)
+
         return upload(mutableURLRequest, stream: stream)
         return upload(mutableURLRequest, stream: stream)
     }
     }
 
 

+ 6 - 5
Source/Validation.swift

@@ -72,9 +72,12 @@ extension Request {
         let subtype: String
         let subtype: String
 
 
         init?(_ string: String) {
         init?(_ string: String) {
-            let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
+            let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
+                                   .substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex)
+                                   .componentsSeparatedByString("/")
 
 
-            if let type = components.first,
+            if let
+                type = components.first,
                 subtype = components.last
                 subtype = components.last
             {
             {
                 self.type = type
                 self.type = type
@@ -110,9 +113,7 @@ extension Request {
                 responseMIMEType = MIMEType(responseContentType)
                 responseMIMEType = MIMEType(responseContentType)
             {
             {
                 for contentType in acceptableContentTypes {
                 for contentType in acceptableContentTypes {
-                    if let acceptableMIMEType = MIMEType(contentType)
-                        where acceptableMIMEType.matches(responseMIMEType)
-                    {
+                    if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
                         return true
                         return true
                     }
                     }
                 }
                 }

+ 2 - 1
Tests/DownloadTests.swift

@@ -198,7 +198,8 @@ class DownloadResponseTestCase: BaseTestCase {
             }
             }
         }
         }
 
 
-        if let lastByteValue = byteValues.last,
+        if let
+            lastByteValue = byteValues.last,
             lastProgressValue = progressValues.last
             lastProgressValue = progressValues.last
         {
         {
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)

+ 10 - 7
Tests/RequestTests.swift

@@ -98,7 +98,7 @@ class RequestResponseTestCase: BaseTestCase {
                 error = responseError
                 error = responseError
 
 
                 expectation.fulfill()
                 expectation.fulfill()
-        }
+            }
 
 
         waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
         waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
 
 
@@ -162,7 +162,8 @@ class RequestResponseTestCase: BaseTestCase {
             }
             }
         }
         }
 
 
-        if let lastByteValue = byteValues.last,
+        if let
+            lastByteValue = byteValues.last,
             lastProgressValue = progressValues.last
             lastProgressValue = progressValues.last
         {
         {
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
@@ -232,7 +233,8 @@ class RequestResponseTestCase: BaseTestCase {
             }
             }
         }
         }
 
 
-        if let lastByteValue = byteValues.last,
+        if let
+            lastByteValue = byteValues.last,
             lastProgressValue = progressValues.last
             lastProgressValue = progressValues.last
         {
         {
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
             let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
@@ -283,17 +285,17 @@ class RequestDescriptionTestCase: BaseTestCase {
 class RequestDebugDescriptionTestCase: BaseTestCase {
 class RequestDebugDescriptionTestCase: BaseTestCase {
     // MARK: Properties
     // MARK: Properties
 
 
-    let manager: Alamofire.Manager = {
-        let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
+    let manager: Manager = {
+        let manager = Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
         manager.startRequestsImmediately = false
         manager.startRequestsImmediately = false
         return manager
         return manager
     }()
     }()
 
 
-    let managerDisallowingCookies: Alamofire.Manager = {
+    let managerDisallowingCookies: Manager = {
         let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
         let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
         configuration.HTTPShouldSetCookies = false
         configuration.HTTPShouldSetCookies = false
 
 
-        let manager = Alamofire.Manager(configuration: configuration)
+        let manager = Manager(configuration: configuration)
         manager.startRequestsImmediately = false
         manager.startRequestsImmediately = false
 
 
         return manager
         return manager
@@ -355,6 +357,7 @@ class RequestDebugDescriptionTestCase: BaseTestCase {
             NSHTTPCookieName: "foo",
             NSHTTPCookieName: "foo",
             NSHTTPCookieValue: "bar",
             NSHTTPCookieValue: "bar",
         ]
         ]
+
         let cookie = NSHTTPCookie(properties: properties)!
         let cookie = NSHTTPCookie(properties: properties)!
         manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
         manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)
 
 

+ 1 - 1
Tests/URLProtocolTests.swift

@@ -149,7 +149,7 @@ class URLProtocolTestCase: BaseTestCase {
                 error = responseError
                 error = responseError
 
 
                 expectation.fulfill()
                 expectation.fulfill()
-        }
+            }
 
 
         waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
         waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)