diff --git a/.circleci/config.yml b/.circleci/config.yml index 0578dcca1..ebf5535ac 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,7 +1,7 @@ version: 2 defaults: &defaults macos: - xcode: 11.0.0 + xcode: 11.3.1 parallelism: 1 shell: /bin/bash --login environment: diff --git a/Changelog.md b/Changelog.md index ac79f900e..1d7d55b60 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,7 @@ # Next +### Changed +- Moya's Swift version is now Swift 5.1. [#1931](https://github.com/Moya/Moya/pull/1931) by [@BasThomas](https://github.com/BasThomas). # [14.0.0] - 2020-02-15 ### Changed diff --git a/Examples/Basic/ViewController.swift b/Examples/Basic/ViewController.swift index cd49bfb8b..37b9a5d1d 100644 --- a/Examples/Basic/ViewController.swift +++ b/Examples/Basic/ViewController.swift @@ -133,7 +133,7 @@ class ViewController: UITableViewController { // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return repos.count + repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { diff --git a/Examples/Multi-Target/ViewController.swift b/Examples/Multi-Target/ViewController.swift index 71717252b..51078a6fa 100644 --- a/Examples/Multi-Target/ViewController.swift +++ b/Examples/Multi-Target/ViewController.swift @@ -135,7 +135,7 @@ class ViewController: UITableViewController { // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return repos.count + repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { diff --git a/Examples/_shared/GiphyAPI.swift b/Examples/_shared/GiphyAPI.swift index e4b1612e3..a9cdfd73e 100644 --- a/Examples/_shared/GiphyAPI.swift +++ b/Examples/_shared/GiphyAPI.swift @@ -8,7 +8,7 @@ public enum Giphy { } extension Giphy: TargetType { - public var baseURL: URL { return URL(string: "https://upload.giphy.com")! } // swiftlint:disable:this force_unwrapping + public var baseURL: URL { URL(string: "https://upload.giphy.com")! } // swiftlint:disable:this force_unwrapping public var path: String { switch self { case .upload: @@ -35,9 +35,7 @@ extension Giphy: TargetType { } } - public var headers: [String: String]? { - return nil - } + public var headers: [String: String]? { nil } // swiftlint:disable:next force_unwrapping static let animatedBirdData = Data(base64Encoded: "R0lGODlhJAAlAMMDAAAAAP/yAB0bAP///5mZmREAAHNzc/7+/hsZAP/xAPr69//0AB4bAGZmZgAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFZAAOACwAAAAAJAAlAAAEY9DJSau9OOvNu/9gKI5kaZ5oqq5s675wLM90DNx3ewc8n6eAntCHCvIYjACyBzgZGYcDVEosPaOEQ5YaaJKu0jDXOwKLx9YeMrlmpofwrskYr77rcqd6aXfSfWQqOD81hYYYEQAh+QQFCgAOACwNABYACQAGAAAEDjDISau1bGaZmQ/edgURACH5BAlkAA4ALAAAAAAkACUAAAQ+0MlJq7046827/2AojmRpnmiqrmzrvnAsz3Rt3yvDOLrLHIdfkCUkHIzDFfAnJAKDz12up5PirtisdsulRQAAIfkECRQADgAsCQAQABIAFQAABHfQuSKrlRRPbTP9RhFeWGgATliIZLqy09piMg1faha/11tPhlll5DighBXAQXJEOppNBkJKRTCTDmlgy91OoQwuAuElb5vmAEIxHrO5DElYrWDX12+1I42v+/MBDHNlbW0LYmldil1ji2qJYnuOjlYShVJjmG0SEQAh+QQJCgAOACwKAA4ADwAVAAAEVtBJCWqd2NXA+cVAJ3pTOI4AdaLaem4dwwSyCNPHweSzZ+4HQpDn4wB3R9KPRwykWsZZjaQB9EaMT8qK3VImsnBJkylTPuazJV21GJ6ZrdxgfsPXoE8EACH5BAkAAA4ALAIAEAAfAA8AAARf0MlJJ7i36q1v+F/GjRZohuQIgAwTtCCQbut7HMztBjKJlbYDQahDSX5HTK+WwzlxRqVsKaoFmztecnm0eFguWEzk6HGYp8/OPDuqT+t2xdqqx+Tz9B0/t4bYfBRSbREAIfkECQAADgAsCwAHAA8AFgAABF/QOQCavI1eqXff2TZZXlgC3sd9GSpOFUe+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cMMXUmljVq8Wj0l1otWEVY4RRCaHWc+yeoUurcvn9jilAsXlb3u7k7/vmXB+f09NaBEAIfkECQAADgAsCwAHAA8AGAAABGPQOQCavI1eqXff2TZZXlgC3sd9GSpOFUe+junS3JRSN7wGQGBHAwAyGIGjUFdMHg6MJzLgKkYPBKyUOjFKoVtq8woOU4JHZDp4Drrf7bc8LnejmkYlm1O3X/BzInRiODwqDhEAIfkECQoADgAsCgAMAA8AFwAABFrQSQlqndjVwPnFAMcwwehNYXkczEoGAKUeBO3CmuiyN5y2u95GZBq9fJ2kErlcDpvJWIp4xOWgJ83UGdNolZduV2tBUTJoKXpdXqMs4zTcEDeHAYY1fdx+dyMAIfkECQoADgAsCQAaABIACwAABEHQSclQvWhqVwNjHhhYm8gcx5kGbCYhrEoc8xpTMXqq3ejAOR0qBQyxYh9LcnFEFI/Q6OjZpLZ+0qzv5VR+Kl1XBAAh+QQJCgAOACwJAAwADwAPAAAEP9BJCWqd2NXA+cVAJ3pTyDFMgHYAdR4HA6dBa8oHkc/ePce8mu8X3JxWKJpwxCSZmiQNlFXqJKmgZy9TsrQwEQAh+QQJCgAOACwKABQADwAPAAAEP9BJCWqd2NXA+cVAJ3pTyDFMgHYAdR4HA6dBa8oHkc/ePce8mu8X3JxWKJpwxCSZmiQNlFXqJKmgZy9TsrQwEQAh+QQFCgAOACwKAA8ADwAPAAAEP9BJCWqd2NXA+cVAJ3pTyDFMgHYAdR4HA6dBa8oHkc/ePce8mu8X3JxWKJpwxCSZmiQNlFXqJKmgZy9TsrQwEQA7", options: [])! diff --git a/Examples/_shared/GitHubAPI.swift b/Examples/_shared/GitHubAPI.swift index 739196c2d..1d4b151c9 100644 --- a/Examples/_shared/GitHubAPI.swift +++ b/Examples/_shared/GitHubAPI.swift @@ -22,7 +22,7 @@ let gitHubProvider = MoyaProvider(plugins: [NetworkLoggerPlugin(configur private extension String { var urlEscaped: String { - return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } @@ -33,7 +33,7 @@ public enum GitHub { } extension GitHub: TargetType { - public var baseURL: URL { return URL(string: "https://api.github.com")! } + public var baseURL: URL { URL(string: "https://api.github.com")! } public var path: String { switch self { case .zen: @@ -44,9 +44,8 @@ extension GitHub: TargetType { return "/users/\(name.urlEscaped)/repos" } } - public var method: Moya.Method { - return .get - } + public var method: Moya.Method { .get } + public var task: Task { switch self { case .userRepositories: @@ -73,13 +72,12 @@ extension GitHub: TargetType { return "[{\"name\": \"\(name)\"}]".data(using: String.Encoding.utf8)! } } - public var headers: [String: String]? { - return nil - } + public var headers: [String: String]? { nil } + } public func url(_ route: TargetType) -> String { - return route.baseURL.appendingPathComponent(route.path).absoluteString + route.baseURL.appendingPathComponent(route.path).absoluteString } // MARK: - Response Handlers diff --git a/Examples/_shared/GitHubUserContentAPI.swift b/Examples/_shared/GitHubUserContentAPI.swift index 3ef92663d..6f93a0a51 100644 --- a/Examples/_shared/GitHubUserContentAPI.swift +++ b/Examples/_shared/GitHubUserContentAPI.swift @@ -8,7 +8,7 @@ public enum GitHubUserContent { } extension GitHubUserContent: TargetType { - public var baseURL: URL { return URL(string: "https://raw.githubusercontent.com")! } // swiftlint:disable:this force_unwrapping + public var baseURL: URL { URL(string: "https://raw.githubusercontent.com")! } // swiftlint:disable:this force_unwrapping public var path: String { switch self { case .downloadMoyaWebContent(let contentPath): @@ -33,9 +33,8 @@ extension GitHubUserContent: TargetType { return Giphy.animatedBirdData } } - public var headers: [String: String]? { - return nil - } + public var headers: [String: String]? { nil } + } private let defaultDownloadDestination: DownloadDestination = { temporaryURL, response in diff --git a/Moya.podspec b/Moya.podspec index b4e3583f2..09164fd51 100644 --- a/Moya.podspec +++ b/Moya.podspec @@ -19,7 +19,7 @@ Pod::Spec.new do |s| s.watchos.deployment_target = '3.0' s.source = { :git => "https://github.com/Moya/Moya.git", :tag => s.version } s.default_subspec = "Core" - s.swift_version = '5.0' + s.swift_version = '5.1' s.cocoapods_version = '>= 1.4.0' s.subspec "Core" do |ss| diff --git a/Moya.xcodeproj/project.pbxproj b/Moya.xcodeproj/project.pbxproj index 99942596c..b0c3de57a 100644 --- a/Moya.xcodeproj/project.pbxproj +++ b/Moya.xcodeproj/project.pbxproj @@ -72,6 +72,7 @@ A6304A7E74FA3B04C9B10B63 /* AccessTokenPluginSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31BAAD7EC02607A52AD3EF1E /* AccessTokenPluginSpec.swift */; }; A8C55515DFA147BE4159B40A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EFCB6731C60D3830DA5D2CB /* Response.swift */; }; AB5048DC5042B016964EE958 /* MoyaProvider+Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 371C174EF53873DE04BB159E /* MoyaProvider+Reactive.swift */; }; + B2CD7F4F23A6F1BA007F67AC /* Atomic.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2CD7F4E23A6F1BA007F67AC /* Atomic.swift */; }; B4ABD55950B0E70BF44E79C6 /* MoyaProviderIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82E52DC541FD052ABA625D2A /* MoyaProviderIntegrationTests.swift */; }; B5A7124CF285D8EC7F89C1AD /* CredentialsPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 884642F58B074C95261DCA86 /* CredentialsPlugin.swift */; }; B950CAA84C0656EB11E316FB /* MultiTargetSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D11E4BE1D5112E6972AD09F /* MultiTargetSpec.swift */; }; @@ -204,6 +205,7 @@ 9C38151BF038BA0B61EF5A62 /* TargetType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TargetType.swift; sourceTree = ""; }; B184F8E91A84A02E209EEB91 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MultipartFormData.swift; sourceTree = ""; }; B1F68927EA26EBDB45E82C8C /* MoyaProviderSpec.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MoyaProviderSpec.swift; sourceTree = ""; }; + B2CD7F4E23A6F1BA007F67AC /* Atomic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Atomic.swift; sourceTree = ""; }; C79C5F376B4A2C3F70051980 /* Error+MoyaSpec.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Error+MoyaSpec.swift"; sourceTree = ""; }; C841AA621AEC61FAEA0CA019 /* MoyaProvider+ReactiveSpec.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "MoyaProvider+ReactiveSpec.swift"; sourceTree = ""; }; CC115388D44D0DB7A753E9BB /* AccessTokenPlugin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AccessTokenPlugin.swift; sourceTree = ""; }; @@ -308,6 +310,7 @@ 331A6D3090D9773091435406 /* Moya */ = { isa = PBXGroup; children = ( + B2CD7F4E23A6F1BA007F67AC /* Atomic.swift */, 149749421F8923EC00FA4900 /* AnyEncodable.swift */, 5C2B20158E599EDBE51D7AB2 /* Cancellable.swift */, 3FF1994427C5440527B03B31 /* Endpoint.swift */, @@ -832,6 +835,7 @@ 3AF7063CBE1F9626FB32D933 /* Cancellable.swift in Sources */, 85F6042E22A018BB00063320 /* RequestTypeWrapper.swift in Sources */, 49C61E884A595E94758B5643 /* Endpoint.swift in Sources */, + B2CD7F4F23A6F1BA007F67AC /* Atomic.swift in Sources */, FB223B5C3B7D4AA5261E25EA /* Image.swift in Sources */, EDBA10DB0D0E35C1474AAB4D /* Moya+Alamofire.swift in Sources */, 15D3A2BD1223B59E2BBE09F0 /* MoyaError.swift in Sources */, diff --git a/Moya.xcodeproj/xcshareddata/xcschemes/Moya.xcscheme b/Moya.xcodeproj/xcshareddata/xcschemes/Moya.xcscheme index c098cc881..925d32b18 100644 --- a/Moya.xcodeproj/xcshareddata/xcschemes/Moya.xcscheme +++ b/Moya.xcodeproj/xcshareddata/xcschemes/Moya.xcscheme @@ -24,8 +24,8 @@ diff --git a/Rakefile b/Rakefile index c19cc9358..612decbec 100644 --- a/Rakefile +++ b/Rakefile @@ -63,8 +63,8 @@ end def device_os return { - ios: "13.0", - tvos: "13.0" + ios: "13.3", + tvos: "13.3" } end diff --git a/Sources/Moya/Atomic.swift b/Sources/Moya/Atomic.swift new file mode 100644 index 000000000..339f59ff2 --- /dev/null +++ b/Sources/Moya/Atomic.swift @@ -0,0 +1,31 @@ +// +// Atomic.swift +// Moya +// +// Created by Luciano Almeida on 15/12/19. +// + +import Foundation + +@propertyWrapper +final class Atomic { + private var lock: NSRecursiveLock = NSRecursiveLock() + + private var value: Value + + var wrappedValue: Value { + get { + lock.lock(); defer { lock.unlock() } + return value + } + + set { + lock.lock(); defer { lock.unlock() } + value = newValue + } + } + + init(wrappedValue value: Value) { + self.value = value + } +} diff --git a/Sources/Moya/Cancellable.swift b/Sources/Moya/Cancellable.swift index 9a9c783f1..368271cad 100644 --- a/Sources/Moya/Cancellable.swift +++ b/Sources/Moya/Cancellable.swift @@ -11,7 +11,7 @@ public protocol Cancellable { internal class CancellableWrapper: Cancellable { internal var innerCancellable: Cancellable = SimpleCancellable() - var isCancelled: Bool { return innerCancellable.isCancelled } + var isCancelled: Bool { innerCancellable.isCancelled } internal func cancel() { innerCancellable.cancel() diff --git a/Sources/Moya/Endpoint.swift b/Sources/Moya/Endpoint.swift index dae0504e9..590d91c07 100755 --- a/Sources/Moya/Endpoint.swift +++ b/Sources/Moya/Endpoint.swift @@ -50,12 +50,12 @@ open class Endpoint { /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with added HTTP header fields. open func adding(newHTTPHeaderFields: [String: String]) -> Endpoint { - return Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: add(httpHeaderFields: newHTTPHeaderFields)) + Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: add(httpHeaderFields: newHTTPHeaderFields)) } /// Convenience method for creating a new `Endpoint` with the same properties as the receiver, but with replaced `task` parameter. open func replacing(task: Task) -> Endpoint { - return Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: httpHeaderFields) + Endpoint(url: url, sampleResponseClosure: sampleResponseClosure, method: method, task: task, httpHeaderFields: httpHeaderFields) } fileprivate func add(httpHeaderFields headers: [String: String]?) -> [String: String]? { diff --git a/Sources/Moya/Moya+Alamofire.swift b/Sources/Moya/Moya+Alamofire.swift index 93f0bd959..1e77a7c68 100644 --- a/Sources/Moya/Moya+Alamofire.swift +++ b/Sources/Moya/Moya+Alamofire.swift @@ -26,7 +26,7 @@ public typealias DownloadDestination = Alamofire.DownloadRequest.Destination /// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins. extension Request: RequestType { public var sessionHeaders: [String: String] { - return delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] ?? [:] + delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] ?? [:] } } @@ -107,22 +107,10 @@ extension DownloadRequest: Requestable { } final class MoyaRequestInterceptor: RequestInterceptor { - private let lock: NSRecursiveLock = NSRecursiveLock() - var prepare: ((URLRequest) -> URLRequest)? - private var internalWillSend: ((URLRequest) -> Void)? - - var willSend: ((URLRequest) -> Void)? { - get { - lock.lock(); defer { lock.unlock() } - return internalWillSend - } - set { - lock.lock(); defer { lock.unlock() } - internalWillSend = newValue - } - } + @Atomic + var willSend: ((URLRequest) -> Void)? init(prepare: ((URLRequest) -> URLRequest)? = nil, willSend: ((URLRequest) -> Void)? = nil) { self.prepare = prepare diff --git a/Sources/Moya/MoyaProvider+Defaults.swift b/Sources/Moya/MoyaProvider+Defaults.swift index 0f97f69b1..d0e949327 100644 --- a/Sources/Moya/MoyaProvider+Defaults.swift +++ b/Sources/Moya/MoyaProvider+Defaults.swift @@ -3,7 +3,7 @@ import Foundation /// These functions are default mappings to `MoyaProvider`'s properties: endpoints, requests, session etc. public extension MoyaProvider { final class func defaultEndpointMapping(for target: Target) -> Endpoint { - return Endpoint( + Endpoint( url: URL(target: target).absoluteString, sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, diff --git a/Sources/Moya/MoyaProvider+Internal.swift b/Sources/Moya/MoyaProvider+Internal.swift index 212c9a0c5..070fae8c6 100644 --- a/Sources/Moya/MoyaProvider+Internal.swift +++ b/Sources/Moya/MoyaProvider+Internal.swift @@ -31,18 +31,14 @@ public extension MoyaProvider { } if trackInflights { - lock.lock() var inflightCompletionBlocks = self.inflightRequests[endpoint] inflightCompletionBlocks?.append(pluginsWithCompletion) - self.inflightRequests[endpoint] = inflightCompletionBlocks - lock.unlock() + self.internalInflightRequests[endpoint] = inflightCompletionBlocks if inflightCompletionBlocks != nil { return cancellableToken } else { - lock.lock() - self.inflightRequests[endpoint] = [pluginsWithCompletion] - lock.unlock() + self.internalInflightRequests[endpoint] = [pluginsWithCompletion] } } @@ -65,10 +61,7 @@ public extension MoyaProvider { let networkCompletion: Moya.Completion = { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach { $0(result) } - - self.lock.lock() - self.inflightRequests.removeValue(forKey: endpoint) - self.lock.unlock() + self.internalInflightRequests.removeValue(forKey: endpoint) } else { pluginsWithCompletion(result) } @@ -167,7 +160,7 @@ private extension MoyaProvider { private func interceptor(target: Target) -> MoyaRequestInterceptor { return MoyaRequestInterceptor(prepare: { [weak self] urlRequest in return self?.plugins.reduce(urlRequest) { $1.prepare($0, target: target) } ?? urlRequest - }) + }) } private func setup(interceptor: MoyaRequestInterceptor, with target: Target, and request: Request) { diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index 0c6381feb..a2fef1da4 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -35,9 +35,7 @@ public struct ProgressResponse { } /// A Boolean value stating whether the request is completed. - public var completed: Bool { - return response != nil - } + public var completed: Bool { response != nil } } /// A protocol representing a minimal interface for a MoyaProvider. @@ -83,7 +81,10 @@ open class MoyaProvider: MoyaProviderType { public let trackInflights: Bool - open internal(set) var inflightRequests: [Endpoint: [Moya.Completion]] = [:] + open var inflightRequests: [Endpoint: [Moya.Completion]] { internalInflightRequests } + + @Atomic + var internalInflightRequests: [Endpoint: [Moya.Completion]] = [:] /// Propagated to Alamofire as callback queue. If nil - the Alamofire default (as of their API in 2017 - the main queue) will be used. let callbackQueue: DispatchQueue? @@ -110,7 +111,7 @@ open class MoyaProvider: MoyaProviderType { /// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`. open func endpoint(_ token: Target) -> Endpoint { - return endpointClosure(token) + endpointClosure(token) } /// Designated request-making method. Returns a `Cancellable` token to cancel the request later. @@ -179,18 +180,14 @@ public extension MoyaProvider { // at least add some class functions to allow easy access to common stubbing closures. /// Do not stub. - final class func neverStub(_: Target) -> Moya.StubBehavior { - return .never - } + final class func neverStub(_: Target) -> Moya.StubBehavior { .never } /// Return a response immediately. - final class func immediatelyStub(_: Target) -> Moya.StubBehavior { - return .immediate - } + final class func immediatelyStub(_: Target) -> Moya.StubBehavior { .immediate } /// Return a response after a delay. final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { - return { _ in return .delayed(seconds: seconds) } + return { _ in .delayed(seconds: seconds) } } } diff --git a/Sources/Moya/MultiTarget.swift b/Sources/Moya/MultiTarget.swift index 19cb7014d..d1f137e6c 100644 --- a/Sources/Moya/MultiTarget.swift +++ b/Sources/Moya/MultiTarget.swift @@ -11,39 +11,25 @@ public enum MultiTarget: TargetType { } /// The embedded target's base `URL`. - public var path: String { - return target.path - } + public var path: String { target.path } /// The baseURL of the embedded target. - public var baseURL: URL { - return target.baseURL - } + public var baseURL: URL { target.baseURL } /// The HTTP method of the embedded target. - public var method: Moya.Method { - return target.method - } + public var method: Moya.Method { target.method } /// The sampleData of the embedded target. - public var sampleData: Data { - return target.sampleData - } + public var sampleData: Data { target.sampleData } /// The `Task` of the embedded target. - public var task: Task { - return target.task - } + public var task: Task { target.task } /// The `ValidationType` of the embedded target. - public var validationType: ValidationType { - return target.validationType - } + public var validationType: ValidationType { target.validationType } /// The headers of the embedded target. - public var headers: [String: String]? { - return target.headers - } + public var headers: [String: String]? { target.headers } /// The embedded `TargetType`. public var target: TargetType { diff --git a/Sources/Moya/Plugin.swift b/Sources/Moya/Plugin.swift index e0705c6c4..3bbe309fd 100644 --- a/Sources/Moya/Plugin.swift +++ b/Sources/Moya/Plugin.swift @@ -21,10 +21,10 @@ public protocol PluginType { } public extension PluginType { - func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { return request } + func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { request } func willSend(_ request: RequestType, target: TargetType) { } func didReceive(_ result: Result, target: TargetType) { } - func process(_ result: Result, target: TargetType) -> Result { return result } + func process(_ result: Result, target: TargetType) -> Result { result } } /// Request type used by `willSend` plugin function. diff --git a/Sources/Moya/RequestTypeWrapper.swift b/Sources/Moya/RequestTypeWrapper.swift index 192310b4d..263d8b21f 100644 --- a/Sources/Moya/RequestTypeWrapper.swift +++ b/Sources/Moya/RequestTypeWrapper.swift @@ -3,13 +3,9 @@ import Foundation // Workaround for new asynchronous handling of Alamofire's request creation. struct RequestTypeWrapper: RequestType { - var request: URLRequest? { - return _urlRequest - } + var request: URLRequest? { _urlRequest } - var sessionHeaders: [String: String] { - return _request.sessionHeaders - } + var sessionHeaders: [String: String] { _request.sessionHeaders } private var _request: Request private var _urlRequest: URLRequest? diff --git a/Sources/Moya/Response.swift b/Sources/Moya/Response.swift index df338cc27..a52167731 100644 --- a/Sources/Moya/Response.swift +++ b/Sources/Moya/Response.swift @@ -24,16 +24,14 @@ public final class Response: CustomDebugStringConvertible, Equatable { /// A text description of the `Response`. public var description: String { - return "Status Code: \(statusCode), Data Length: \(data.count)" + "Status Code: \(statusCode), Data Length: \(data.count)" } /// A text description of the `Response`. Suitable for debugging. - public var debugDescription: String { - return description - } + public var debugDescription: String { description } public static func == (lhs: Response, rhs: Response) -> Bool { - return lhs.statusCode == rhs.statusCode + lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } @@ -63,7 +61,7 @@ public extension Response { - throws: `MoyaError.statusCode` when others are encountered. */ func filter(statusCode: Int) throws -> Response { - return try filter(statusCodes: statusCode...statusCode) + try filter(statusCodes: statusCode...statusCode) } /** @@ -72,7 +70,7 @@ public extension Response { - throws: `MoyaError.statusCode` when others are encountered. */ func filterSuccessfulStatusCodes() throws -> Response { - return try filter(statusCodes: 200...299) + try filter(statusCodes: 200...299) } /** @@ -81,7 +79,7 @@ public extension Response { - throws: `MoyaError.statusCode` when others are encountered. */ func filterSuccessfulStatusAndRedirectCodes() throws -> Response { - return try filter(statusCodes: 200...399) + try filter(statusCodes: 200...399) } /// Maps data received from the signal into an Image. diff --git a/Sources/Moya/TargetType.swift b/Sources/Moya/TargetType.swift index d24749125..357b3ce45 100644 --- a/Sources/Moya/TargetType.swift +++ b/Sources/Moya/TargetType.swift @@ -28,7 +28,5 @@ public protocol TargetType { public extension TargetType { /// The type of validation to perform on the request. Default is `.none`. - var validationType: ValidationType { - return .none - } + var validationType: ValidationType { .none } } diff --git a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift index 65b272c60..4a525d6ab 100644 --- a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift +++ b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift @@ -10,7 +10,7 @@ public extension Reactive where Base: MoyaProviderType { /// Designated request-making method. func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer { - return SignalProducer { [weak base] observer, lifetime in + SignalProducer { [weak base] observer, lifetime in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): @@ -29,12 +29,7 @@ public extension Reactive where Base: MoyaProviderType { /// Designated request-making method with progress. func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer { - let progressBlock: (Signal.Observer) -> (ProgressResponse) -> Void = { observer in - return { progress in - observer.send(value: progress) - } - } - + let progressBlock = Signal.Observer.send(value:) let response: SignalProducer = SignalProducer { [weak base] observer, lifetime in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in switch result { diff --git a/Sources/ReactiveMoya/SignalProducer+Response.swift b/Sources/ReactiveMoya/SignalProducer+Response.swift index 408c6db7d..23121b9b3 100644 --- a/Sources/ReactiveMoya/SignalProducer+Response.swift +++ b/Sources/ReactiveMoya/SignalProducer+Response.swift @@ -15,56 +15,56 @@ public extension SignalProducerProtocol where Value == Response, Error == MoyaEr /// Filters out responses that don't fall within the given range, generating errors when others are encountered. func filter(statusCodes: R) -> SignalProducer where R.Bound == Int { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.filter(statusCodes: statusCodes) } } } /// Filters out responses that have the specified `statusCode`. func filter(statusCode: Int) -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.filter(statusCode: statusCode) } } } /// Filters out responses where `statusCode` falls within the range 200 - 299. func filterSuccessfulStatusCodes() -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.filterSuccessfulStatusCodes() } } } /// Filters out responses where `statusCode` falls within the range 200 - 399 func filterSuccessfulStatusAndRedirectCodes() -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.filterSuccessfulStatusAndRedirectCodes() } } } /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. func mapImage() -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.mapImage() } } } /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. func mapJSON(failsOnEmptyData: Bool = true) -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.mapJSON(failsOnEmptyData: failsOnEmptyData) } } } /// Maps received data at key path into a String. If the conversion fails, the signal errors. func mapString(atKeyPath keyPath: String? = nil) -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.mapString(atKeyPath: keyPath) } } } /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> SignalProducer { - return producer.flatMap(.latest) { response in + producer.flatMap(.latest) { response in unwrapThrowable { try response.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData) } } } @@ -79,7 +79,7 @@ private func unwrapThrowable(throwable: () throws -> T) -> SignalProducer Single { - return Single.create { [weak base] single in + Single.create { [weak base] single in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): @@ -33,12 +33,8 @@ public extension Reactive where Base: MoyaProviderType { /// Designated request-making method with progress. func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable { - let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in - return { progress in - observer.onNext(progress) - } - } + let progressBlock = AnyObserver.onNext let response: Observable = Observable.create { [weak base] observer in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in switch result { diff --git a/Sources/RxMoya/Observable+Response.swift b/Sources/RxMoya/Observable+Response.swift index dfc32a6d5..a1164d127 100644 --- a/Sources/RxMoya/Observable+Response.swift +++ b/Sources/RxMoya/Observable+Response.swift @@ -15,42 +15,42 @@ public extension ObservableType where Element == Response { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. func filter(statusCodes: R) -> Observable where R.Bound == Int { - return flatMap { Observable.just(try $0.filter(statusCodes: statusCodes)) } + flatMap { Observable.just(try $0.filter(statusCodes: statusCodes)) } } /// Filters out responses that has the specified `statusCode`. func filter(statusCode: Int) -> Observable { - return flatMap { Observable.just(try $0.filter(statusCode: statusCode)) } + flatMap { Observable.just(try $0.filter(statusCode: statusCode)) } } /// Filters out responses where `statusCode` falls within the range 200 - 299. func filterSuccessfulStatusCodes() -> Observable { - return flatMap { Observable.just(try $0.filterSuccessfulStatusCodes()) } + flatMap { Observable.just(try $0.filterSuccessfulStatusCodes()) } } /// Filters out responses where `statusCode` falls within the range 200 - 399 func filterSuccessfulStatusAndRedirectCodes() -> Observable { - return flatMap { Observable.just(try $0.filterSuccessfulStatusAndRedirectCodes()) } + flatMap { Observable.just(try $0.filterSuccessfulStatusAndRedirectCodes()) } } /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. func mapImage() -> Observable { - return flatMap { Observable.just(try $0.mapImage()) } + flatMap { Observable.just(try $0.mapImage()) } } /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. func mapJSON(failsOnEmptyData: Bool = true) -> Observable { - return flatMap { Observable.just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } + flatMap { Observable.just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } } /// Maps received data at key path into a String. If the conversion fails, the signal errors. func mapString(atKeyPath keyPath: String? = nil) -> Observable { - return flatMap { Observable.just(try $0.mapString(atKeyPath: keyPath)) } + flatMap { Observable.just(try $0.mapString(atKeyPath: keyPath)) } } /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Observable { - return flatMap { Observable.just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } + flatMap { Observable.just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } } } @@ -62,7 +62,7 @@ public extension ObservableType where Element == ProgressResponse { - returns: response associated with ProgressResponse object */ func filterCompleted() -> Observable { - return self + self .filter { $0.completed } .flatMap { progress -> Observable in // Just a formatlity to satisfy the compiler (completed progresses have responses). @@ -79,6 +79,6 @@ public extension ObservableType where Element == ProgressResponse { - returns: observable of progress events */ func filterProgress() -> Observable { - return self.filter { !$0.completed }.map { $0.progress } + self.filter { !$0.completed }.map { $0.progress } } } diff --git a/Sources/RxMoya/Single+Response.swift b/Sources/RxMoya/Single+Response.swift index 2902203d0..fbf498648 100644 --- a/Sources/RxMoya/Single+Response.swift +++ b/Sources/RxMoya/Single+Response.swift @@ -15,41 +15,41 @@ public extension PrimitiveSequence where Trait == SingleTrait, Element == Respon /// Filters out responses that don't fall within the given closed range, generating errors when others are encountered. func filter(statusCodes: R) -> Single where R.Bound == Int { - return flatMap { .just(try $0.filter(statusCodes: statusCodes)) } + flatMap { .just(try $0.filter(statusCodes: statusCodes)) } } /// Filters out responses that have the specified `statusCode`. func filter(statusCode: Int) -> Single { - return flatMap { .just(try $0.filter(statusCode: statusCode)) } + flatMap { .just(try $0.filter(statusCode: statusCode)) } } /// Filters out responses where `statusCode` falls within the range 200 - 299. func filterSuccessfulStatusCodes() -> Single { - return flatMap { .just(try $0.filterSuccessfulStatusCodes()) } + flatMap { .just(try $0.filterSuccessfulStatusCodes()) } } /// Filters out responses where `statusCode` falls within the range 200 - 399 func filterSuccessfulStatusAndRedirectCodes() -> Single { - return flatMap { .just(try $0.filterSuccessfulStatusAndRedirectCodes()) } + flatMap { .just(try $0.filterSuccessfulStatusAndRedirectCodes()) } } /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. func mapImage() -> Single { - return flatMap { .just(try $0.mapImage()) } + flatMap { .just(try $0.mapImage()) } } /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. func mapJSON(failsOnEmptyData: Bool = true) -> Single { - return flatMap { .just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } + flatMap { .just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } } /// Maps received data at key path into a String. If the conversion fails, the signal errors. func mapString(atKeyPath keyPath: String? = nil) -> Single { - return flatMap { .just(try $0.mapString(atKeyPath: keyPath)) } + flatMap { .just(try $0.mapString(atKeyPath: keyPath)) } } /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Single { - return flatMap { .just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } + flatMap { .just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } } } diff --git a/Tests/MoyaTests/EndpointSpec.swift b/Tests/MoyaTests/EndpointSpec.swift index 49dff904d..ee37637e8 100644 --- a/Tests/MoyaTests/EndpointSpec.swift +++ b/Tests/MoyaTests/EndpointSpec.swift @@ -80,19 +80,19 @@ final class EndpointSpec: QuickSpec { describe("successful converting to urlRequest") { context("when task is .requestPlain") { itBehavesLike("endpoint with no request property changed") { - return ["task": Task.requestPlain, "endpoint": self.simpleGitHubEndpoint] + ["task": Task.requestPlain, "endpoint": self.simpleGitHubEndpoint] } } context("when task is .uploadFile") { itBehavesLike("endpoint with no request property changed") { - return ["task": Task.uploadFile(URL(string: "https://google.com")!), "endpoint": self.simpleGitHubEndpoint] + ["task": Task.uploadFile(URL(string: "https://google.com")!), "endpoint": self.simpleGitHubEndpoint] } } context("when task is .uploadMultipart") { itBehavesLike("endpoint with no request property changed") { - return ["task": Task.uploadMultipart([]), "endpoint": self.simpleGitHubEndpoint] + ["task": Task.uploadMultipart([]), "endpoint": self.simpleGitHubEndpoint] } } @@ -373,12 +373,12 @@ enum Empty { extension Empty: TargetType { // None of these matter since the Empty has no cases and can't be instantiated. - var baseURL: URL { return URL(string: "http://example.com")! } - var path: String { return "" } - var method: Moya.Method { return .get } - var parameters: [String: Any]? { return nil } - var parameterEncoding: ParameterEncoding { return URLEncoding.default } - var task: Task { return .requestPlain } - var sampleData: Data { return Data() } - var headers: [String: String]? { return nil } + var baseURL: URL { URL(string: "http://example.com")! } + var path: String { "" } + var method: Moya.Method { .get } + var parameters: [String: Any]? { nil } + var parameterEncoding: ParameterEncoding { URLEncoding.default } + var task: Task { .requestPlain } + var sampleData: Data { Data() } + var headers: [String: String]? { nil } } diff --git a/Tests/MoyaTests/Error+MoyaSpec.swift b/Tests/MoyaTests/Error+MoyaSpec.swift index 276896c88..f2f02cea5 100644 --- a/Tests/MoyaTests/Error+MoyaSpec.swift +++ b/Tests/MoyaTests/Error+MoyaSpec.swift @@ -2,7 +2,7 @@ import Nimble import Moya public func beOfSameErrorType(_ expectedValue: MoyaError) -> Predicate { - return Predicate { expression -> PredicateResult in + Predicate { expression -> PredicateResult in let test: Bool if let value = try expression.evaluate() { switch value { diff --git a/Tests/MoyaTests/MoyaProvider+RxSpec.swift b/Tests/MoyaTests/MoyaProvider+RxSpec.swift index 5d94d0171..1d930512f 100644 --- a/Tests/MoyaTests/MoyaProvider+RxSpec.swift +++ b/Tests/MoyaTests/MoyaProvider+RxSpec.swift @@ -220,17 +220,17 @@ final class MoyaProviderRxSpec: QuickSpec { context("the callback queue is provided with the request") { it("invokes the callback on the request queue") { let requestQueue = DispatchQueue(label: UUID().uuidString) - var callbackQueueLabel: String? + let callbackQueueLabel = Atomic(wrappedValue: nil) waitUntil(action: { completion in provider.rx.request(.zen, callbackQueue: requestQueue) .subscribe(onSuccess: { _ in - callbackQueueLabel = DispatchQueue.currentLabel + callbackQueueLabel.wrappedValue = DispatchQueue.currentLabel completion() }).disposed(by: disposeBag) }) - expect(callbackQueueLabel) == requestQueue.label + expect(callbackQueueLabel.wrappedValue) == requestQueue.label } } diff --git a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift index 29ce874e4..ba47c4013 100644 --- a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift +++ b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift @@ -11,7 +11,7 @@ import OHHTTPStubsSwift @testable import ReactiveMoya func beIdenticalToResponse(_ expectedValue: Moya.Response) -> Predicate { - return Predicate { expression in + Predicate { expression in let test: Bool if let value = try expression.evaluate(), value == expectedValue { test = true @@ -119,18 +119,19 @@ final class MoyaProviderIntegrationTests: QuickSpec { } it("uses a background queue") { - var isMainThread: Bool? + + let callbackQueueLabel = Atomic(wrappedValue: nil) let callbackQueue = DispatchQueue(label: "background_queue", attributes: .concurrent) let target: GitHub = .zen waitUntil { done in provider.request(target, callbackQueue: callbackQueue) { _ in - isMainThread = Thread.isMainThread + callbackQueueLabel.wrappedValue = DispatchQueue.currentLabel done() } } - expect(isMainThread) == false + expect(callbackQueueLabel.wrappedValue) == "background_queue" } it("uses the main queue") { diff --git a/Tests/MoyaTests/MoyaProviderSpec.swift b/Tests/MoyaTests/MoyaProviderSpec.swift index ca4632376..8024eeea8 100644 --- a/Tests/MoyaTests/MoyaProviderSpec.swift +++ b/Tests/MoyaTests/MoyaProviderSpec.swift @@ -436,7 +436,7 @@ final class MoyaProviderSpec: QuickSpec { it("returns identical sample response") { let response = HTTPURLResponse(url: URL(string: "http://example.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)! let endpointResolution: MoyaProvider.EndpointClosure = { target in - return Endpoint(url: URL(target: target).absoluteString, sampleResponseClosure: { .response(response, target.sampleData) }, method: target.method, task: target.task, httpHeaderFields: target.headers) + Endpoint(url: URL(target: target).absoluteString, sampleResponseClosure: { .response(response, target.sampleData) }, method: target.method, task: target.task, httpHeaderFields: target.headers) } let provider = MoyaProvider(endpointClosure: endpointResolution, stubClosure: MoyaProvider.immediatelyStub) @@ -1079,7 +1079,7 @@ final class MoyaProviderSpec: QuickSpec { context("response contains invalid status code") { it("returns an error") { let endpointClosure = { (target: GitHub) -> Endpoint in - return Endpoint( + Endpoint( url: URL(target: target).absoluteString, sampleResponseClosure: { .networkResponse(400, target.sampleData) }, method: target.method, @@ -1113,7 +1113,7 @@ final class MoyaProviderSpec: QuickSpec { context("response contains valid status code") { it("returns a response") { let endpointClosure = { (target: GitHub) -> Endpoint in - return Endpoint( + Endpoint( url: URL(target: target).absoluteString, sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, diff --git a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift index 25cf30dbc..6b10ae615 100644 --- a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift +++ b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift @@ -106,7 +106,7 @@ final class NetworkLoggerPluginSpec: QuickSpec { let plugin = NetworkLoggerPlugin() plugin.configuration.output = customLoggerOutput plugin.configuration.logOptions = .verbose - plugin.configuration.formatter.requestData = { _ in return "formatted request body" } + plugin.configuration.formatter.requestData = { _ in "formatted request body" } return plugin }() @@ -120,7 +120,7 @@ final class NetworkLoggerPluginSpec: QuickSpec { let pluginWithEntryFormatter: NetworkLoggerPlugin = { let plugin = NetworkLoggerPlugin() plugin.configuration.output = customLoggerOutput - plugin.configuration.formatter.entry = { _, _, _ in return "formatted log entry" } + plugin.configuration.formatter.entry = { _, _, _ in "formatted log entry" } return plugin }() @@ -136,7 +136,7 @@ final class NetworkLoggerPluginSpec: QuickSpec { let pluginWithResponseDataFormatter: NetworkLoggerPlugin = { let plugin = NetworkLoggerPlugin() plugin.configuration.output = customLoggerOutput - plugin.configuration.formatter.responseData = { _ in return "formatted response body" } + plugin.configuration.formatter.responseData = { _ in "formatted response body" } plugin.configuration.logOptions = .verbose return plugin }() @@ -161,16 +161,12 @@ private class TestStreamRequest: RequestType { } var sessionHeaders: [String: String] { - return ["Content-Type": "application/badJson", "Accept-Language": "en-US"] + ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - return self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - return self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") @@ -188,16 +184,12 @@ private class TestBodyRequest: RequestType { } var sessionHeaders: [String: String] { - return ["Content-Type": "application/badJson", "Accept-Language": "en-US"] + ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - return self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - return self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") @@ -215,16 +207,12 @@ private class TestCurlBodyRequest: RequestType { } var sessionHeaders: [String: String] { - return ["Content-Type": "application/badJson", "Accept-Language": "en-US"] + ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - return self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - return self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler(["$ curl -i", "-H \"Content-Type: application/json\"", "-d \"cool body\"", "\"https://api.github.com/zen\""].joined(separator: " \\\n\t")) @@ -233,21 +221,13 @@ private class TestCurlBodyRequest: RequestType { } private class TestNilRequest: RequestType { - var request: URLRequest? { - return nil - } + var request: URLRequest? { nil } - var sessionHeaders: [String: String] { - return [:] - } + var sessionHeaders: [String: String] { [:] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - return self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - return self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") diff --git a/Tests/MoyaTests/NimbleHelpers.swift b/Tests/MoyaTests/NimbleHelpers.swift index 52cf27bb1..90e180d7d 100644 --- a/Tests/MoyaTests/NimbleHelpers.swift +++ b/Tests/MoyaTests/NimbleHelpers.swift @@ -2,7 +2,7 @@ import Nimble /// A Nimble matcher that succeeds when at least one of the substrings public func containOne(of substrings: String...) -> Predicate { - return containOne(of: substrings) + containOne(of: substrings) } /// A Nimble matcher that succeeds when at least one of the substrings diff --git a/Tests/MoyaTests/PropertyListEncoding.swift b/Tests/MoyaTests/PropertyListEncoding.swift index 15cf2e5b5..a43e81c9d 100644 --- a/Tests/MoyaTests/PropertyListEncoding.swift +++ b/Tests/MoyaTests/PropertyListEncoding.swift @@ -5,13 +5,13 @@ internal struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. - static var `default`: PropertyListEncoding { return PropertyListEncoding() } + static var `default`: PropertyListEncoding { PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. - static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + static var xml: PropertyListEncoding { PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. - static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + static var binary: PropertyListEncoding { PropertyListEncoding(format: .binary) } /// The property list serialization format. let format: PropertyListSerialization.PropertyListFormat diff --git a/Tests/MoyaTests/RxTestHelpers.swift b/Tests/MoyaTests/RxTestHelpers.swift index 1e48eae45..9f0edb498 100644 --- a/Tests/MoyaTests/RxTestHelpers.swift +++ b/Tests/MoyaTests/RxTestHelpers.swift @@ -2,11 +2,7 @@ import Moya import RxSwift extension Response { - func asObservable() -> Observable { - return Observable.just(self) - } + func asObservable() -> Observable { Observable.just(self) } - func asSingle() -> Single { - return Single.just(self) - } + func asSingle() -> Single { Single.just(self) } } diff --git a/Tests/MoyaTests/SignalProducer+MoyaSpec.swift b/Tests/MoyaTests/SignalProducer+MoyaSpec.swift index 3998f687b..3696b7358 100644 --- a/Tests/MoyaTests/SignalProducer+MoyaSpec.swift +++ b/Tests/MoyaTests/SignalProducer+MoyaSpec.swift @@ -5,7 +5,7 @@ import Nimble import Foundation private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer { - return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil)) + SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil)) } final class SignalProducerMoyaSpec: QuickSpec { diff --git a/Tests/MoyaTests/TestHelpers.swift b/Tests/MoyaTests/TestHelpers.swift index a3d3899fe..9ca48fdb1 100644 --- a/Tests/MoyaTests/TestHelpers.swift +++ b/Tests/MoyaTests/TestHelpers.swift @@ -14,7 +14,7 @@ enum GitHub { } extension GitHub: TargetType { - var baseURL: URL { return URL(string: "https://api.github.com")! } + var baseURL: URL { URL(string: "https://api.github.com")! } var path: String { switch self { case .zen: @@ -24,13 +24,9 @@ extension GitHub: TargetType { } } - var method: Moya.Method { - return .get - } + var method: Moya.Method { .get } - var task: Task { - return .requestPlain - } + var task: Task { .requestPlain } var sampleData: Data { switch self { @@ -41,13 +37,9 @@ extension GitHub: TargetType { } } - var validationType: ValidationType { - return .successAndRedirectCodes - } + var validationType: ValidationType { .successAndRedirectCodes } - var headers: [String: String]? { - return nil - } + var headers: [String: String]? { nil } } extension GitHub: Equatable { @@ -61,7 +53,7 @@ extension GitHub: Equatable { } func url(_ route: TargetType) -> String { - return route.baseURL.appendingPathComponent(route.path).absoluteString + route.baseURL.appendingPathComponent(route.path).absoluteString } let failureEndpointClosure = { (target: GitHub) -> Endpoint in @@ -77,7 +69,7 @@ enum HTTPBin: TargetType, AccessTokenAuthorizable { case uploadMultipart([MultipartFormData], [String: Any]?) case validatedUploadMultipart([MultipartFormData], [String: Any]?, [Int]) - var baseURL: URL { return URL(string: "http://httpbin.org")! } + var baseURL: URL { URL(string: "http://httpbin.org")! } var path: String { switch self { case .basicAuth: @@ -124,9 +116,7 @@ enum HTTPBin: TargetType, AccessTokenAuthorizable { } } - var headers: [String: String]? { - return nil - } + var headers: [String: String]? { nil } var validationType: ValidationType { switch self { @@ -153,7 +143,7 @@ public enum GitHubUserContent { } extension GitHubUserContent: TargetType { - public var baseURL: URL { return URL(string: "https://raw.githubusercontent.com")! } + public var baseURL: URL { URL(string: "https://raw.githubusercontent.com")! } public var path: String { switch self { case .downloadMoyaWebContent(let contentPath), .requestMoyaWebContent(let contentPath): @@ -172,9 +162,7 @@ extension GitHubUserContent: TargetType { return nil } } - public var parameterEncoding: ParameterEncoding { - return URLEncoding.default - } + public var parameterEncoding: ParameterEncoding { URLEncoding.default } public var task: Task { switch self { case .downloadMoyaWebContent: @@ -190,9 +178,7 @@ extension GitHubUserContent: TargetType { } } - public var headers: [String: String]? { - return nil - } + public var headers: [String: String]? { nil } } // MARK: - Upload Multipart Helpers @@ -214,7 +200,7 @@ extension HTTPBin { // MARK: - String Helpers extension String { var urlEscaped: String { - return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } @@ -222,7 +208,7 @@ extension String { // https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160613/002280.html extension DispatchQueue { class var currentLabel: String? { - return String(validatingUTF8: __dispatch_queue_get_label(nil)) + String(validatingUTF8: __dispatch_queue_get_label(nil)) } } @@ -250,12 +236,12 @@ extension ImageType { class TestClass { } static var testImage: ImageType { - return Image(data: testImageData)! + Image(data: testImageData)! } #if canImport(UIKit) func asJPEGRepresentation(_ compression: CGFloat) -> Data? { - return jpegData(compressionQuality: compression) + jpegData(compressionQuality: compression) } #elseif canImport(AppKit) func asJPEGRepresentation(_ compression: CGFloat) -> Data? { diff --git a/docs/Authentication.md b/docs/Authentication.md index e92109bc1..faea1b910 100644 --- a/docs/Authentication.md +++ b/docs/Authentication.md @@ -11,7 +11,7 @@ when initializing your provider. ```swift let provider = MoyaProvider(plugins: [CredentialsPlugin { _ -> URLCredential? in - return URLCredential(user: "user", password: "passwd", persistence: .none) + URLCredential(user: "user", password: "passwd", persistence: .none) } ]) ``` diff --git a/docs/Examples/AlamofireValidation.md b/docs/Examples/AlamofireValidation.md index fad6dfde5..193ccdd58 100644 --- a/docs/Examples/AlamofireValidation.md +++ b/docs/Examples/AlamofireValidation.md @@ -5,7 +5,7 @@ When a request is configured with Alamofire validation, Moya will internally cal ```swift // MARK: - TargetType Protocol Implementation extension MyService: TargetType { - var baseURL: URL { return URL(string: "https://api.myservice.com")! } + var baseURL: URL { URL(string: "https://api.myservice.com")! } var path: String { switch self { case .zen: diff --git a/docs/Examples/Assets.md b/docs/Examples/Assets.md index f3bd715ca..8320309eb 100644 --- a/docs/Examples/Assets.md +++ b/docs/Examples/Assets.md @@ -21,21 +21,15 @@ enum Asset: TargetType { } } - var path: String { - return "/assets/" + assetName - } + var path: String { "/assets/" + assetName } - var localLocation: URL { - return assetDir.appendingPathComponent(assetName) - } + var localLocation: URL { assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - return { _, _ in return (self.localLocation, .removePreviousFile) } + return { _, _ in (self.localLocation, .removePreviousFile) } } - var task: Task { - return .downloadDestination(downloadDestination) - } + var task: Task { .downloadDestination(downloadDestination) } /* Rest of TargetType diff --git a/docs/Examples/AuthPlugin.md b/docs/Examples/AuthPlugin.md index c2b02bda3..da83b92b6 100644 --- a/docs/Examples/AuthPlugin.md +++ b/docs/Examples/AuthPlugin.md @@ -56,7 +56,7 @@ struct AuthPlugin: PluginType { let source = TokenSource() let provider = MoyaProvider( plugins: [ - AuthPlugin(tokenClosure: { return source.token }) + AuthPlugin(tokenClosure: { source.token }) ] ) diff --git a/docs/Examples/Basic.md b/docs/Examples/Basic.md index f76873757..416c72018 100644 --- a/docs/Examples/Basic.md +++ b/docs/Examples/Basic.md @@ -20,7 +20,7 @@ target (at compile time). You can see that parameters needed for requests can be ```swift // MARK: - TargetType Protocol Implementation extension MyService: TargetType { - var baseURL: URL { return URL(string: "https://api.myservice.com")! } + var baseURL: URL { URL(string: "https://api.myservice.com")! } var path: String { switch self { case .zen: @@ -77,12 +77,10 @@ extension MyService: TargetType { // MARK: - Helpers private extension String { var urlEscaped: String { - return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } - var utf8Encoded: Data { - return data(using: .utf8)! - } + var utf8Encoded: Data { Data(self.utf8) } } ``` @@ -124,7 +122,7 @@ You can also set up custom endpoints to alter the default behavior to your needs ```swift let endpointClosure = { (target: MyService) -> Endpoint in - return Endpoint(url: URL(target: target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers) + Endpoint(url: URL(target: target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers) } ``` diff --git a/docs/Examples/MultiTarget.md b/docs/Examples/MultiTarget.md index e83d694d8..6e01c18ed 100644 --- a/docs/Examples/MultiTarget.md +++ b/docs/Examples/MultiTarget.md @@ -86,7 +86,7 @@ instead of `MoyaResponse` as ```swift extension MultiMoyaProvider { func requestDecoded(_ target: T, completion: @escaping (_ result: Result<[T.ResultType], Moya.Error>) -> ()) -> Cancellable { - return request(target) { result in + request(target) { result in switch result { case .success(let response): if let parsed = T.ResultType.parse(try! response.mapJSON()) { diff --git a/docs/Targets.md b/docs/Targets.md index 6cd23135f..84e2b5182 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -24,7 +24,7 @@ providers). Here's the beginning of our extension: ```swift extension GitHub: TargetType { - public var baseURL: URL { return URL(string: "https://api.github.com")! } + public var baseURL: URL { URL(string: "https://api.github.com")! } } ``` @@ -150,7 +150,7 @@ Here's an example extension that allows you to easily escape normal strings ```swift extension String { var urlEscaped: String { - return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } ``` diff --git a/docs_CN/Authentication.md b/docs_CN/Authentication.md index 038d074fa..f8b6f3b1b 100644 --- a/docs_CN/Authentication.md +++ b/docs_CN/Authentication.md @@ -9,7 +9,7 @@ HTTP身份验证是一个 username/password HTTP协议内置的验证方式. 如 ```swift let provider = MoyaProvider(plugins: [CredentialsPlugin { _ -> URLCredential? in - return URLCredential(user: "user", password: "passwd", persistence: .none) + URLCredential(user: "user", password: "passwd", persistence: .none) } ]) ``` diff --git a/docs_CN/Examples/AlamofireValidation.md b/docs_CN/Examples/AlamofireValidation.md index fa91e2782..f4e1f9f08 100644 --- a/docs_CN/Examples/AlamofireValidation.md +++ b/docs_CN/Examples/AlamofireValidation.md @@ -6,7 +6,7 @@ ```swift // MARK: - TargetType Protocol Implementation extension MyService: TargetType { - var baseURL: URL { return URL(string: "https://api.myservice.com")! } + var baseURL: URL { URL(string: "https://api.myservice.com")! } var path: String { switch self { case .zen: diff --git a/docs_CN/Examples/Assets.md b/docs_CN/Examples/Assets.md index 3841be4b5..d60316503 100644 --- a/docs_CN/Examples/Assets.md +++ b/docs_CN/Examples/Assets.md @@ -22,21 +22,15 @@ enum Asset: TargetType { } } - var path: String { - return "/assets/" + assetName - } + var path: String { "/assets/" + assetName } - var localLocation: URL { - return assetDir.appendingPathComponent(assetName) - } + var localLocation: URL { assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - return { _, _ in return (self.localLocation, .removePreviousFile) } + return { _, _ in (self.localLocation, .removePreviousFile) } } - var task: Task { - return .downloadDestination(downloadDestination) - } + var task: Task { .downloadDestination(downloadDestination) } /* Rest of TargetType diff --git a/docs_CN/Examples/AuthPlugin.md b/docs_CN/Examples/AuthPlugin.md index 05765a6f6..2fd907c9b 100644 --- a/docs_CN/Examples/AuthPlugin.md +++ b/docs_CN/Examples/AuthPlugin.md @@ -50,7 +50,7 @@ struct AuthPlugin: PluginType { let source = TokenSource() let provider = MoyaProvider( plugins: [ - AuthPlugin(tokenClosure: { return source.token }) + AuthPlugin(tokenClosure: { source.token }) ] ) diff --git a/docs_CN/Examples/Basic.md b/docs_CN/Examples/Basic.md index 4958240e9..042a35709 100644 --- a/docs_CN/Examples/Basic.md +++ b/docs_CN/Examples/Basic.md @@ -74,11 +74,11 @@ extension MyService: TargetType { // MARK: - Helpers private extension String { var urlEscaped: String { - return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } var utf8Encoded: Data { - return data(using: .utf8)! + Data(self.utf8) } } ``` @@ -118,7 +118,7 @@ JSON, images, text, 或者任何您希望从endpoint得到的. ```swift let endpointClosure = { (target: MyService) -> Endpoint in - return Endpoint(url: URL(target: target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task) + Endpoint(url: URL(target: target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task) } ``` diff --git a/docs_CN/Examples/MultiTarget.md b/docs_CN/Examples/MultiTarget.md index 2915f67a0..fc1c2fc7b 100644 --- a/docs_CN/Examples/MultiTarget.md +++ b/docs_CN/Examples/MultiTarget.md @@ -57,7 +57,7 @@ enum UserApi: DecodableTargetType { ```swift extension MultiMoyaProvider { func requestDecoded(_ target: T, completion: @escaping (_ result: Result<[T.ResultType], Moya.Error>) -> ()) -> Cancellable { - return request(target) { result in + request(target) { result in switch result { case .success(let response): if let parsed = T.ResultType.parse(try! response.mapJSON()) { diff --git a/docs_CN/Targets.md b/docs_CN/Targets.md index e884f1c43..17c3fc459 100644 --- a/docs_CN/Targets.md +++ b/docs_CN/Targets.md @@ -17,7 +17,7 @@ Targets必须遵循 `TargetType`协议。 `TargetType`协议要求一个`baseURL ```swift extension GitHub: TargetType { - public var baseURL: URL { return URL(string: "https://api.github.com")! } + public var baseURL: URL { URL(string: "https://api.github.com")! } } ``` @@ -131,7 +131,7 @@ URLs的转义 ```swift extension String { var urlEscaped: String { - return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } ```