From f1aebb24ac17222908c6534b0b9eb51ba4f2446c Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 17:53:41 +0200 Subject: [PATCH 01/21] Update podspec to Swift 5.1 --- Moya.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Moya.podspec b/Moya.podspec index c6e2671dd..bbb034491 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| From 53a1cd4a5dc24e42c811a37ece88b19b10746316 Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 17:53:53 +0200 Subject: [PATCH 02/21] Run Carthage update --- Cartfile.resolved | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cartfile.resolved b/Cartfile.resolved index acb53591d..f6bc47987 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,6 +1,6 @@ github "Alamofire/Alamofire" "5.0.0-rc.2" github "AliSoftware/OHHTTPStubs" "8.0.0" -github "Quick/Nimble" "v8.0.2" -github "Quick/Quick" "v2.1.0" +github "Quick/Nimble" "v8.0.4" +github "Quick/Quick" "v2.2.0" github "ReactiveCocoa/ReactiveSwift" "6.1.0" github "ReactiveX/RxSwift" "5.0.1" From 0df2876f3d53148ed882c3b06b92002c811204d9 Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 17:56:08 +0200 Subject: [PATCH 03/21] Omit returns in single-expression functions --- Examples/Basic/ViewController.swift | 2 +- Examples/Multi-Target/ViewController.swift | 2 +- Examples/_shared/GiphyAPI.swift | 4 +- Examples/_shared/GitHubAPI.swift | 10 ++--- Examples/_shared/GitHubUserContentAPI.swift | 4 +- Sources/Moya/Cancellable.swift | 2 +- .../Moya/Combine/AnyPublisher+Response.swift | 20 +++++----- .../Moya/Combine/MoyaProvider+Combine.swift | 6 +-- Sources/Moya/Endpoint.swift | 4 +- Sources/Moya/Moya+Alamofire.swift | 2 +- Sources/Moya/MoyaProvider+Defaults.swift | 2 +- Sources/Moya/MoyaProvider+Internal.swift | 6 +-- Sources/Moya/MoyaProvider.swift | 10 ++--- Sources/Moya/MultiTarget.swift | 14 +++---- Sources/Moya/Plugin.swift | 4 +- .../Moya/Plugins/NetworkLoggerPlugin.swift | 2 +- Sources/Moya/RequestTypeWrapper.swift | 4 +- Sources/Moya/Response.swift | 12 +++--- Sources/Moya/TargetType.swift | 2 +- .../ReactiveMoya/MoyaProvider+Reactive.swift | 4 +- .../SignalProducer+Response.swift | 16 ++++---- Sources/RxMoya/MoyaProvider+Rx.swift | 4 +- Sources/RxMoya/Observable+Response.swift | 20 +++++----- Sources/RxMoya/Single+Response.swift | 16 ++++---- Tests/MoyaTests/EndpointSpec.swift | 22 +++++------ Tests/MoyaTests/Error+MoyaSpec.swift | 2 +- .../MoyaTests/MoyaProvider+CombineSpec.swift | 6 +-- .../MoyaTests/MoyaProvider+ReactiveSpec.swift | 4 +- Tests/MoyaTests/MoyaProvider+RxSpec.swift | 6 +-- .../MoyaProviderIntegrationTests.swift | 10 ++--- Tests/MoyaTests/MoyaProviderSpec.swift | 14 +++---- Tests/MoyaTests/NetworkLoggerPluginSpec.swift | 38 +++++++++---------- Tests/MoyaTests/NimbleHelpers.swift | 2 +- Tests/MoyaTests/PropertyListEncoding.swift | 6 +-- Tests/MoyaTests/RxTestHelpers.swift | 4 +- Tests/MoyaTests/SignalProducer+MoyaSpec.swift | 2 +- Tests/MoyaTests/TestHelpers.swift | 28 +++++++------- 37 files changed, 158 insertions(+), 158 deletions(-) diff --git a/Examples/Basic/ViewController.swift b/Examples/Basic/ViewController.swift index e52fc04be..a4cb68edd 100644 --- a/Examples/Basic/ViewController.swift +++ b/Examples/Basic/ViewController.swift @@ -130,7 +130,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..705b8e20d 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: @@ -36,7 +36,7 @@ extension Giphy: TargetType { } public var headers: [String: String]? { - return nil + nil } // swiftlint:disable:next force_unwrapping diff --git a/Examples/_shared/GitHubAPI.swift b/Examples/_shared/GitHubAPI.swift index 8ac0a5eca..ed9b4e143 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: @@ -45,7 +45,7 @@ extension GitHub: TargetType { } } public var method: Moya.Method { - return .get + .get } public var task: Task { switch self { @@ -74,12 +74,12 @@ extension GitHub: TargetType { } } public var headers: [String: String]? { - return nil + 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..ec9af98db 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): @@ -34,7 +34,7 @@ extension GitHubUserContent: TargetType { } } public var headers: [String: String]? { - return nil + nil } } 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/Combine/AnyPublisher+Response.swift b/Sources/Moya/Combine/AnyPublisher+Response.swift index b10704fa1..a04bde284 100644 --- a/Sources/Moya/Combine/AnyPublisher+Response.swift +++ b/Sources/Moya/Combine/AnyPublisher+Response.swift @@ -15,56 +15,56 @@ public extension AnyPublisher where Output == Response, Failure == MoyaError { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. func filter(statusCodes: R) -> AnyPublisher where R.Bound == Int { - return unwrapThrowable { response in + unwrapThrowable { response in try response.filter(statusCodes: statusCodes) } } /// Filters out responses that has the specified `statusCode`. func filter(statusCode: Int) -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in try response.filter(statusCode: statusCode) } } /// Filters out responses where `statusCode` falls within the range 200 - 299. func filterSuccessfulStatusCodes() -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in try response.filterSuccessfulStatusCodes() } } /// Filters out responses where `statusCode` falls within the range 200 - 399 func filterSuccessfulStatusAndRedirectCodes() -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in try response.filterSuccessfulStatusAndRedirectCodes() } } /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. func mapImage() -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in 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) -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in 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) -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in 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) -> AnyPublisher { - return unwrapThrowable { response in + unwrapThrowable { response in try response.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData) } } @@ -79,7 +79,7 @@ public extension AnyPublisher where Output == ProgressResponse, Failure == MoyaE - returns: response associated with ProgressResponse object */ func filterCompleted() -> AnyPublisher { - return self + self .compactMap { $0.response } .eraseToAnyPublisher() } @@ -90,7 +90,7 @@ public extension AnyPublisher where Output == ProgressResponse, Failure == MoyaE - returns: observable of progress events */ func filterProgress() -> AnyPublisher { - return self + self .filter { !$0.completed } .map { $0.progress } .eraseToAnyPublisher() diff --git a/Sources/Moya/Combine/MoyaProvider+Combine.swift b/Sources/Moya/Combine/MoyaProvider+Combine.swift index 0b66bba35..38e22009b 100644 --- a/Sources/Moya/Combine/MoyaProvider+Combine.swift +++ b/Sources/Moya/Combine/MoyaProvider+Combine.swift @@ -13,8 +13,8 @@ public extension MoyaProvider { /// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used. /// - Returns: `AnyPublisher AnyPublisher { - return MoyaPublisher { [weak self] subscriber in - return self?.request(target, callbackQueue: callbackQueue, progress: nil) { result in + MoyaPublisher { [weak self] subscriber in + self?.request(target, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): _ = subscriber.receive(response) @@ -30,7 +30,7 @@ public extension MoyaProvider { /// Designated request-making method with progress. func requestWithProgressPublisher(_ target: Target, callbackQueue: DispatchQueue? = nil) -> AnyPublisher { let progressBlock: (AnySubscriber) -> (ProgressResponse) -> Void = { subscriber in - return { progress in + { progress in _ = subscriber.receive(progress) } } 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 4781317da..fe1291d3f 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] ?? [:] } } 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 e493b47c3..c7ab5c52b 100644 --- a/Sources/Moya/MoyaProvider+Internal.swift +++ b/Sources/Moya/MoyaProvider+Internal.swift @@ -112,7 +112,7 @@ public extension MoyaProvider { /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint, plugins: [PluginType], request: URLRequest) -> (() -> Void) { // swiftlint:disable:this function_parameter_count - return { + { if token.isCancelled { self.cancelCompletion(completion, target: target) return @@ -165,8 +165,8 @@ public extension MoyaProvider { 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 + MoyaRequestInterceptor(prepare: { [weak self] urlRequest in + self?.plugins.reduce(urlRequest) { $1.prepare($0, target: target) } ?? urlRequest }) } diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index f03c424ae..472360be3 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -36,7 +36,7 @@ public struct ProgressResponse { /// A Boolean value stating whether the request is completed. public var completed: Bool { - return response != nil + response != nil } } @@ -108,7 +108,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. @@ -178,17 +178,17 @@ public extension MoyaProvider { /// Do not stub. final class func neverStub(_: Target) -> Moya.StubBehavior { - return .never + .never } /// Return a response immediately. final class func immediatelyStub(_: Target) -> Moya.StubBehavior { - return .immediate + .immediate } /// Return a response after a delay. final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { - return { _ in return .delayed(seconds: seconds) } + { _ in .delayed(seconds: seconds) } } } diff --git a/Sources/Moya/MultiTarget.swift b/Sources/Moya/MultiTarget.swift index 7b813e4ec..64ac32506 100644 --- a/Sources/Moya/MultiTarget.swift +++ b/Sources/Moya/MultiTarget.swift @@ -12,37 +12,37 @@ public enum MultiTarget: TargetType { /// The embedded target's base `URL`. public var path: String { - return target.path + target.path } /// The baseURL of the embedded target. public var baseURL: URL { - return target.baseURL + target.baseURL } /// The HTTP method of the embedded target. public var method: Moya.Method { - return target.method + target.method } /// The sampleData of the embedded target. public var sampleData: Data { - return target.sampleData + target.sampleData } /// The `Task` of the embedded target. public var task: Task { - return target.task + target.task } /// The `ValidationType` of the embedded target. public var validationType: ValidationType { - return target.validationType + target.validationType } /// The headers of the embedded target. public var headers: [String: String]? { - return target.headers + target.headers } /// The embedded `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/Plugins/NetworkLoggerPlugin.swift b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift index 06099c9ee..15214f91f 100644 --- a/Sources/Moya/Plugins/NetworkLoggerPlugin.swift +++ b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift @@ -219,7 +219,7 @@ public extension NetworkLoggerPlugin.Configuration { // MARK: Defaults public static func defaultDataFormatter(_ data: Data) -> String { - return String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" + String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" } public static func defaultEntryFormatter(identifier: String, message: String, target: TargetType) -> String { diff --git a/Sources/Moya/RequestTypeWrapper.swift b/Sources/Moya/RequestTypeWrapper.swift index 192310b4d..07d3ca832 100644 --- a/Sources/Moya/RequestTypeWrapper.swift +++ b/Sources/Moya/RequestTypeWrapper.swift @@ -4,11 +4,11 @@ import Foundation struct RequestTypeWrapper: RequestType { var request: URLRequest? { - return _urlRequest + _urlRequest } var sessionHeaders: [String: String] { - return _request.sessionHeaders + _request.sessionHeaders } private var _request: Request diff --git a/Sources/Moya/Response.swift b/Sources/Moya/Response.swift index df338cc27..84398b605 100644 --- a/Sources/Moya/Response.swift +++ b/Sources/Moya/Response.swift @@ -24,16 +24,16 @@ 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 + 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 +63,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 +72,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 +81,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..16251fb0c 100644 --- a/Sources/Moya/TargetType.swift +++ b/Sources/Moya/TargetType.swift @@ -29,6 +29,6 @@ public extension TargetType { /// The type of validation to perform on the request. Default is `.none`. var validationType: ValidationType { - return .none + .none } } diff --git a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift index 65b272c60..074d654b4 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): @@ -30,7 +30,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 + { progress in observer.send(value: progress) } } diff --git a/Sources/ReactiveMoya/SignalProducer+Response.swift b/Sources/ReactiveMoya/SignalProducer+Response.swift index 408c6db7d..4240a0071 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) } } } diff --git a/Sources/RxMoya/MoyaProvider+Rx.swift b/Sources/RxMoya/MoyaProvider+Rx.swift index ceb3fcd65..7fa6dde0b 100644 --- a/Sources/RxMoya/MoyaProvider+Rx.swift +++ b/Sources/RxMoya/MoyaProvider+Rx.swift @@ -15,7 +15,7 @@ public extension Reactive where Base: MoyaProviderType { /// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used. /// - Returns: Single response object. func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> 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): @@ -34,7 +34,7 @@ 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 + { progress in observer.onNext(progress) } } 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+CombineSpec.swift b/Tests/MoyaTests/MoyaProvider+CombineSpec.swift index cb630e956..e4add2f5f 100644 --- a/Tests/MoyaTests/MoyaProvider+CombineSpec.swift +++ b/Tests/MoyaTests/MoyaProvider+CombineSpec.swift @@ -136,7 +136,7 @@ final class MoyaProviderCombineSpec: QuickSpec { beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) provider = MoyaProvider(trackInflights: true) } @@ -197,7 +197,7 @@ final class MoyaProviderCombineSpec: QuickSpec { //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) + OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) }) provider = MoyaProvider() } @@ -244,7 +244,7 @@ final class MoyaProviderCombineSpec: QuickSpec { beforeEach { stubDescriptor = OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) } diff --git a/Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift b/Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift index be3f89a76..93f510ed5 100644 --- a/Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift +++ b/Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift @@ -104,7 +104,7 @@ final class MoyaProviderReactiveSpec: QuickSpec { var provider: MoyaProvider! beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) provider = MoyaProvider(trackInflights: true) } @@ -149,7 +149,7 @@ final class MoyaProviderReactiveSpec: QuickSpec { //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) + OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) }) provider = MoyaProvider() } diff --git a/Tests/MoyaTests/MoyaProvider+RxSpec.swift b/Tests/MoyaTests/MoyaProvider+RxSpec.swift index 8bdefbd66..c80615eae 100644 --- a/Tests/MoyaTests/MoyaProvider+RxSpec.swift +++ b/Tests/MoyaTests/MoyaProvider+RxSpec.swift @@ -105,7 +105,7 @@ final class MoyaProviderRxSpec: QuickSpec { beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) provider = MoyaProvider(trackInflights: true) } @@ -157,7 +157,7 @@ final class MoyaProviderRxSpec: QuickSpec { //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) + OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) }) provider = MoyaProvider() } @@ -199,7 +199,7 @@ final class MoyaProviderRxSpec: QuickSpec { beforeEach { stubDescriptor = OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) } diff --git a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift index 2356247f6..64ed63768 100644 --- a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift +++ b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift @@ -13,7 +13,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 @@ -32,19 +32,19 @@ final class MoyaProviderIntegrationTests: QuickSpec { beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/users/ashfurrow"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.userProfile("ashfurrow").sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.userProfile("ashfurrow").sampleData, statusCode: 200, headers: nil) }) OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/users/invalid"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.userProfile("invalid").sampleData, statusCode: 400, headers: nil) + OHHTTPStubsResponse(data: GitHub.userProfile("invalid").sampleData, statusCode: 400, headers: nil) }) OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/basic-auth/user/passwd"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: HTTPBin.basicAuth.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: HTTPBin.basicAuth.sampleData, statusCode: 200, headers: nil) }) } diff --git a/Tests/MoyaTests/MoyaProviderSpec.swift b/Tests/MoyaTests/MoyaProviderSpec.swift index 6937dd6a7..b584aad1a 100644 --- a/Tests/MoyaTests/MoyaProviderSpec.swift +++ b/Tests/MoyaTests/MoyaProviderSpec.swift @@ -438,7 +438,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) @@ -682,7 +682,7 @@ final class MoyaProviderSpec: QuickSpec { beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) provider = MoyaProvider(trackInflights: true) } @@ -756,7 +756,7 @@ final class MoyaProviderSpec: QuickSpec { //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) + OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) }) provider = MoyaProvider() } @@ -836,7 +836,7 @@ final class MoyaProviderSpec: QuickSpec { //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: ["Content-Length": ""]).responseTime(-4) + OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: ["Content-Length": ""]).responseTime(-4) }) provider = MoyaProvider() } @@ -985,7 +985,7 @@ final class MoyaProviderSpec: QuickSpec { beforeEach { stubDescriptor = OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in - return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) + OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) } @@ -1081,7 +1081,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, @@ -1115,7 +1115,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..d57ef1901 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,20 +161,20 @@ 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 + self } func authenticate(with credential: URLCredential) -> Self { - return self + self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - return self + self } } @@ -188,20 +188,20 @@ 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 + self } func authenticate(with credential: URLCredential) -> Self { - return self + self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - return self + self } } @@ -215,15 +215,15 @@ 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 + self } func authenticate(with credential: URLCredential) -> Self { - return self + self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { @@ -234,23 +234,23 @@ private class TestCurlBodyRequest: RequestType { private class TestNilRequest: RequestType { var request: URLRequest? { - return nil + nil } var sessionHeaders: [String: String] { - return [:] + [:] } func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - return self + self } func authenticate(with credential: URLCredential) -> Self { - return self + self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - return self + self } } 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..5b751ebc9 100644 --- a/Tests/MoyaTests/RxTestHelpers.swift +++ b/Tests/MoyaTests/RxTestHelpers.swift @@ -3,10 +3,10 @@ import RxSwift extension Response { func asObservable() -> Observable { - return Observable.just(self) + Observable.just(self) } func asSingle() -> Single { - return Single.just(self) + 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 e7558b98a..dcc5fc2a8 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: @@ -25,11 +25,11 @@ extension GitHub: TargetType { } var method: Moya.Method { - return .get + .get } var task: Task { - return .requestPlain + .requestPlain } var sampleData: Data { @@ -42,11 +42,11 @@ extension GitHub: TargetType { } var validationType: ValidationType { - return .successAndRedirectCodes + .successAndRedirectCodes } var headers: [String: String]? { - return nil + nil } } @@ -61,7 +61,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 +77,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: @@ -125,7 +125,7 @@ enum HTTPBin: TargetType, AccessTokenAuthorizable { } var headers: [String: String]? { - return nil + nil } var validationType: ValidationType { @@ -173,7 +173,7 @@ extension GitHubUserContent: TargetType { } } public var parameterEncoding: ParameterEncoding { - return URLEncoding.default + URLEncoding.default } public var task: Task { switch self { @@ -191,7 +191,7 @@ extension GitHubUserContent: TargetType { } public var headers: [String: String]? { - return nil + nil } } @@ -214,7 +214,7 @@ extension HTTPBin { // MARK: - String Helpers extension String { var urlEscaped: String { - return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } } @@ -222,7 +222,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 +250,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? { From c89cf6c20e2b03296df94e7546b3acf305c04a7c Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 17:56:37 +0200 Subject: [PATCH 04/21] Use non-nullable Data to String conversion --- Examples/_shared/GitHubAPI.swift | 2 +- Sources/Moya/Plugins/NetworkLoggerPlugin.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/_shared/GitHubAPI.swift b/Examples/_shared/GitHubAPI.swift index ed9b4e143..91e4d733e 100644 --- a/Examples/_shared/GitHubAPI.swift +++ b/Examples/_shared/GitHubAPI.swift @@ -9,7 +9,7 @@ private func JSONResponseDataFormatter(_ data: Data) -> String { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) - return String(data: prettyData, encoding: .utf8) ?? String() + return String(decoding: prettyData, as: UTF8.self) } catch { return String() } diff --git a/Sources/Moya/Plugins/NetworkLoggerPlugin.swift b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift index 15214f91f..d9a795226 100644 --- a/Sources/Moya/Plugins/NetworkLoggerPlugin.swift +++ b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift @@ -219,7 +219,7 @@ public extension NetworkLoggerPlugin.Configuration { // MARK: Defaults public static func defaultDataFormatter(_ data: Data) -> String { - String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" + String(decoding: data, as: UTF8.self) } public static func defaultEntryFormatter(identifier: String, message: String, target: TargetType) -> String { From 1deff6dfabdb4a530d3e7d784e9db5d64601f38b Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 18:02:36 +0200 Subject: [PATCH 05/21] Add a line to the changelog --- Changelog.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Changelog.md b/Changelog.md index 5dc4d9eae..98f941c27 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,8 @@ # 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-beta.3] - 2019-09-27 ### Fixed From b94ba22e39e3feda065f3547717158d3e6b6117e Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Fri, 4 Oct 2019 19:41:00 +0200 Subject: [PATCH 06/21] Add missing return statements Next time, build and run MoyaTests, not the example project ;p --- Tests/MoyaTests/NetworkLoggerPluginSpec.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift index d57ef1901..462e55c98 100644 --- a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift +++ b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift @@ -174,7 +174,7 @@ private class TestStreamRequest: RequestType { func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - self + return self } } @@ -201,7 +201,7 @@ private class TestBodyRequest: RequestType { func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - self + return self } } @@ -251,6 +251,6 @@ private class TestNilRequest: RequestType { func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") - self + return self } } From f32d6944d88578b1b9560edc34a25fa57705092b Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Thu, 31 Oct 2019 20:01:40 +0100 Subject: [PATCH 07/21] Implicit return in documentation --- docs/Authentication.md | 2 +- docs/Examples/AlamofireValidation.md | 2 +- docs/Examples/Assets.md | 6 +++--- docs/Examples/AuthPlugin.md | 2 +- docs/Examples/Basic.md | 8 ++++---- docs/Examples/MultiTarget.md | 2 +- docs/Targets.md | 4 ++-- docs_CN/Authentication.md | 2 +- docs_CN/Examples/AlamofireValidation.md | 2 +- docs_CN/Examples/Assets.md | 8 ++++---- docs_CN/Examples/AuthPlugin.md | 2 +- docs_CN/Examples/Basic.md | 6 +++--- docs_CN/Examples/MultiTarget.md | 2 +- docs_CN/Targets.md | 4 ++-- 14 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/Authentication.md b/docs/Authentication.md index 4754db330..889896332 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..1f58747ab 100644 --- a/docs/Examples/Assets.md +++ b/docs/Examples/Assets.md @@ -26,15 +26,15 @@ enum Asset: TargetType { } var localLocation: URL { - return assetDir.appendingPathComponent(assetName) + assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - return { _, _ in return (self.localLocation, .removePreviousFile) } + { _, _ in (self.localLocation, .removePreviousFile) } } var task: Task { - return .downloadDestination(downloadDestination) + .downloadDestination(downloadDestination) } /* 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..f24f55005 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,11 +77,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) } } ``` @@ -124,7 +124,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 0f57efe71..7b2b9fc2f 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..34501c70e 100644 --- a/docs_CN/Examples/Assets.md +++ b/docs_CN/Examples/Assets.md @@ -23,19 +23,19 @@ enum Asset: TargetType { } var path: String { - return "/assets/" + assetName + "/assets/" + assetName } var localLocation: URL { - return assetDir.appendingPathComponent(assetName) + assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - return { _, _ in return (self.localLocation, .removePreviousFile) } + { _, _ in (self.localLocation, .removePreviousFile) } } var task: Task { - return .downloadDestination(downloadDestination) + .downloadDestination(downloadDestination) } /* 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)! } } ``` From 0605fe1739ed00b55e37e95dcf01b3925d91f83f Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Sat, 23 Nov 2019 19:52:29 +0100 Subject: [PATCH 08/21] Another implicit return --- Tests/MoyaTests/TestHelpers.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/MoyaTests/TestHelpers.swift b/Tests/MoyaTests/TestHelpers.swift index dcc5fc2a8..21d1a3594 100644 --- a/Tests/MoyaTests/TestHelpers.swift +++ b/Tests/MoyaTests/TestHelpers.swift @@ -153,7 +153,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): From d98bdfa6217018f308f108fa618411e075e93c35 Mon Sep 17 00:00:00 2001 From: Bas Broek Date: Sat, 23 Nov 2019 19:53:25 +0100 Subject: [PATCH 09/21] Fix Danger warning --- Sources/Moya/MoyaProvider.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index 472360be3..1e7dc0162 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -156,7 +156,7 @@ open class MoyaProvider: MoyaProviderType { // swiftlint:enable function_parameter_count } -/// Mark: Stubbing +// Mark: Stubbing /// Controls how stub responses are returned. public enum StubBehavior { From 4b697f0e4ec601761dab07d872aabecdd27e92ee Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Sun, 15 Dec 2019 20:15:32 -0300 Subject: [PATCH 10/21] Improving atomic code by using Atomic property wrapper --- Moya.xcodeproj/project.pbxproj | 4 +++ Sources/Moya/Atomic.swift | 31 +++++++++++++++++++ Sources/Moya/Moya+Alamofire.swift | 16 ++-------- Sources/Moya/MoyaProvider+Internal.swift | 13 ++------ Sources/Moya/MoyaProvider.swift | 8 +++-- .../ReactiveMoya/MoyaProvider+Reactive.swift | 3 +- .../SignalProducer+Response.swift | 2 +- Sources/RxMoya/MoyaProvider+Rx.swift | 3 +- 8 files changed, 48 insertions(+), 32 deletions(-) create mode 100644 Sources/Moya/Atomic.swift 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/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/Moya+Alamofire.swift b/Sources/Moya/Moya+Alamofire.swift index d33bd2d1a..1e77a7c68 100644 --- a/Sources/Moya/Moya+Alamofire.swift +++ b/Sources/Moya/Moya+Alamofire.swift @@ -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+Internal.swift b/Sources/Moya/MoyaProvider+Internal.swift index fa0a52f44..0f37f132b 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) } diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index 5b8341401..ce391f0ea 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -83,7 +83,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? @@ -189,8 +192,7 @@ public extension MoyaProvider { } /// Return a response after a delay. - final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { - { _ in .delayed(seconds: seconds) } + final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { { _ in .delayed(seconds: seconds) } } } diff --git a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift index 074d654b4..38e5d6f3b 100644 --- a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift +++ b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift @@ -29,8 +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 - { progress in + let progressBlock: (Signal.Observer) -> (ProgressResponse) -> Void = { observer in { progress in observer.send(value: progress) } } diff --git a/Sources/ReactiveMoya/SignalProducer+Response.swift b/Sources/ReactiveMoya/SignalProducer+Response.swift index 4240a0071..23121b9b3 100644 --- a/Sources/ReactiveMoya/SignalProducer+Response.swift +++ b/Sources/ReactiveMoya/SignalProducer+Response.swift @@ -79,7 +79,7 @@ private func unwrapThrowable(throwable: () throws -> T) -> SignalProducer Observable { - let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in - { progress in + let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in { progress in observer.onNext(progress) } } From 2dc1da50d535718ad4ac2070cee2e081717f5570 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Tue, 18 Feb 2020 00:06:55 -0300 Subject: [PATCH 11/21] TSAN: A couple of tests data races caught by TSAN fixed --- Tests/MoyaTests/MoyaProvider+RxSpec.swift | 6 +++--- Tests/MoyaTests/MoyaProviderIntegrationTests.swift | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) 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 3e1290ad0..7738438be 100644 --- a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift +++ b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift @@ -119,18 +119,19 @@ final class MoyaProviderIntegrationTests: QuickSpec { } it("uses a background queue") { - var isMainThread: Bool? + + let isMainThread = 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 + isMainThread.wrappedValue = Thread.isMainThread done() } } - expect(isMainThread) == false + expect(isMainThread.wrappedValue) == false } it("uses the main queue") { From 886042de242948c93ba11b642066085288dcb6cb Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 21 Feb 2020 22:27:27 -0300 Subject: [PATCH 12/21] [tests] Disable debug executable in test action to fix tvOS Tests. --- Moya.xcodeproj/xcshareddata/xcschemes/Moya.xcscheme | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 @@ From 547274027f7aa6a21709be1719de1a300f90b2ce Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 21 Feb 2020 22:42:26 -0300 Subject: [PATCH 13/21] [CI] Updating CI environment to Xcode 11.3.1 and iOS 13.3 --- .circleci/config.yml | 2 +- Rakefile | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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/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 From e220519cbb09fdc6df708b7537effbe839941c93 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Fri, 21 Feb 2020 22:50:24 -0300 Subject: [PATCH 14/21] One liners --- Examples/_shared/GiphyAPI.swift | 4 +-- Examples/_shared/GitHubAPI.swift | 10 +++----- Examples/_shared/GitHubUserContentAPI.swift | 5 ++-- Sources/Moya/MoyaProvider.swift | 8 ++---- Sources/Moya/MultiTarget.swift | 28 ++++++--------------- Sources/Moya/Response.swift | 4 +-- Sources/Moya/TargetType.swift | 4 +-- Tests/MoyaTests/TestHelpers.swift | 16 +++--------- 8 files changed, 22 insertions(+), 57 deletions(-) diff --git a/Examples/_shared/GiphyAPI.swift b/Examples/_shared/GiphyAPI.swift index 705b8e20d..a9cdfd73e 100644 --- a/Examples/_shared/GiphyAPI.swift +++ b/Examples/_shared/GiphyAPI.swift @@ -35,9 +35,7 @@ extension Giphy: TargetType { } } - public var headers: [String: String]? { - 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+junC1I26FMMEvo4GADwcGMbfjlI8EJzJwLCJRB6lk4DWytVKiV4f8OdlAr1osvmcLoO3PnE5i65j6fY5J6+9reoqKTkiEQAh+QQJAAAOACwDAA4AHQAPAAAEZxC4SasDGNsNjNwXwDDBqIFdaFhAeRzMS36U99lVGx8ELwc0Ve10ccGOMCAFsxpqWgHjjhSVZJrCUDQ6KlGrNyKLuy1Tg6Dl9kuupjnmUXeLfhfLeKV9nC/X91B9f3tafoOEExliaREAIfkECQoADgAsCgAMAA8AFwAABFrQSQlqndjVwPnFQCd6UziOANUxTMB2qekeB0O3nmkfBH/nnJ1NCAzefsVg6wXTuE7PlPMpwkmnrCyJopHlNFyK5Sq9ZkrhM9qsFrPP43dpbJDH7gZ1nfyZSyMAIfkECQoADgAsCgAJAA8AFwAABFrQSQlqndjVwPnFQCd6UziOANUxTMB2qekeB0O3nmkfBH/nnJ1NCAzefsVg6wXTuE7PlPMpwkmnrCyJopHlNFyK5Sq9ZkrhM9qsFrPP43dpbJDH7gZ1nfyZSyMAIfkECQAADgAsAgANAB8ADwAABF/QyUknuLfqrW/4X8ZRWAWAaGiKDsaeH8MEMghYbiuVe3wcjN8scNuJisWWh/YjHJzA0GvU8gGvUSK1Awpih9otCVWr2cRjWiqmQlvY5La7F5OZw3P6Gp83plh9JDliEQAh+QQJAAAOACwKAAUADwAXAAAEYdA5AJq8jV6pd9/ZNlleWALex30ZKk4VR76O6dLclFI3vDKMALCjAQgPBwYyiGoeDwToMuAyKpPYJHUS6F6/XaoxDBQGwxRveH1Oq9nosRdYRnPX+O09b+fwuz0weCo7hBEAIfkECQAADgAsAwAMAB0ADwAABGcQuEmrAxjbDYzcF8AwwaiBXWhYQHkczEt+lPfZVRsfBC8HNFXtdHHBjjAgBbMaaloB444UlWSawlA0OipRqzcii7stU4Og5fZLrqY55lF3i34Xy3ilfZwv1/dQfX97Wn6DhBMZYmkRACH5BAkKAA4ALAoABwAPABcAAARa0EkJap3Y1cD5xUAnelM4jgDVMUzAdqnpHgdDt55pHwR/55ydTQgM3n7FYOsF07hOz5TzKcJJp6wsiaKR5TRciuUqvWZK4TParBazz+N3aWyQx+4GdZ38mUsjACH5BAkKAA4ALAoABAAPABcAAARa0EkJap3Y1cD5xUAnelM4jgDVMUzAdqnpHgdDt55pHwR/55ydTQgM3n7FYOsF07hOz5TzKcJJp6wsiaKR5TRciuUqvWZK4TParBazz+N3aWyQx+4GdZ38mUsjACH5BAkAAA4ALAIACwAfAA8AAARf0MlJJ7i36q1v+F/GjRZohuQIgAwTtCCQbut7HMztBjKJlbYDQahDSX5HTK+WwzlxRqVsKaoFmztecnm0eFguWEzk6HGYp8/OPDuqT+t2xdqqx+Tz9B0/t4bYfBRSbREAIfkECQAADgAsCgAEAA8AFwAABGHQOQCavI1eqXff2TZZXlgC3sd9GSpOFUe+junS3JRSN7wyjACwowEIDwcGMohqHg8E6DLgMiqT2CR1Euhev12qMQwUBsMUb3h9TqvZ6LEXWEZz1/jtPW/n8Ls9MHgqO4QRACH5BAkAAA4ALAMACgAdAA8AAARnELhJq2MMYMuBkZyjHQdDZqFoiJ41HgR8gtQH2hUQmGVfBjTWaoKb6HanUwBIAbRqTslxidkxlkupcyg0Hq9YLNhJJIemYDE2mDKGMfAwuz0N25lt190+z9f3fX57WXl0f2aFhlGJEQAh+QQJCgAOACwKAAUADwAXAAAEWtBJCWqd2NXA+cVAJ3pTOI4A1TFMwHap6R4HQ7eeaR8Ef+ecnU0IDN5+xWDrBdO4Ts+U8ynCSaesLImikeU0XIrlKr1mSuEz2qwWs8/jd2lskMfuBnWd/JlLIwAh+QQJCgAOACwKAAIADwAXAAAEWtBJCWqd2NXA+cVAJ3pTOI4A1TFMwHap6R4HQ7eeaR8Ef+ecnU0IDN5+xWDrBdO4Ts+U8ynCSaesLImikeU0XIrlKr1mSuEz2qwWs8/jd2lskMfuBnWd/JlLIwAh+QQJAAAOACwCAAkAHwAPAAAEX9DJSSe4t+qtb/hfxo0WaIbkCIAME7QgkG7rexzM7QYyiZW2A0GoQ0l+R0yvlsM5cUalbCmqBZs7XnJ5tHhYLlhM5OhxmKfPzjw7qk/rdsXaqsfk8/QdP7eG2HwUUm0RACH5BAkAAA4ALAoAAwAPABcAAARh0DkAmryNXql339k2WV5YAt7HfRkqThVHvo7p0tyUUje8MowAsKMBCA8HBjKIah4PBOgy4DIqk9gkdRLoXr9dqjEMFAbDFG94fU6r2eixF1hGc9f47T1v5/C7PTB4KjuEEQAh+QQJAAAOACwDAAoAHQAPAAAEZxC4SasDGNsNjNwXwDDBqIFdaFhAeRzMS36U99lVGx8ELwc0Ve10ccGOMCAFsxpqWgHjjhSVZJrCUDQ6KlGrNyKLuy1Tg6Dl9kuupjnmUXeLfhfLeKV9nC/X91B9f3tafoOEExliaREAIfkECQoADgAsCgAGAA8AFgAABE/QSQlqndjVwPnFQCd6UziOAHWi2npurgjHnsl0N5fPTB/0uUDKFEu1aMbZK6kh1jSUEkPAMEKvGRA2C/pwKRZrNgwwiEvNpoFrtloyb0cEACH5BAkAAA4ALAIADQAfABAAAARi0MlJJ7i36q1v+F/GjRZohuQIgAwTtCCQbut7HMztBjKJlbYDQahDSX5HTK+WwzlxRqVsKWLenlBecnm0eD4tVzgmcvQ4tZP6PDOr3+x2+q1tU+bjmL0yP8X3Zn1lgHxKbREAIfkECQAADgAsCgAJAA8AFwAABF/QOQCavI1eqXff2TZZXlgC3sd9GSpOFUe+junS3JRSN7wGQGBHAwAyGIGjUFdMHg6MJzLgKkYPBKyUOjFKoVtq8woOU4JHZDp4Drrf7bcc1ZSzOe71HW/npuA9OyoOEQAh+QQJAAAOACwDAA4AHQAQAAAEZxC4SasDGNsNjNwXEIyjBnahYYkBw7Rv8FHeV1cscxw6X+KoyW0i6hEOR98Mo6JlLqOeTvrLNFPE3I63jZmGHJLrNSbNQDiSei1Dh9nssxsKX8vnrKhLfcfXzXMnf32BIXaEhVlPgREAIfkECQoADgAsCgAMAA8AFQAABFfQSQlqndjVwPnFgBduATCF5XEAKmpq6UHIbQnHLLuKHKOuPwZPJGSQSqiOUnlcLk1JZPQVddo0VSYV+4RSTpaXZpwpY8Xm88ccBhjQJyzWYH6LLRm8IwIAIfkECQAADgAsAgANAB8AEAAABGHQyUknuLfqrW/4X8aN1scwwRmSI2AeBwOjAcBilCsfBD/XOZEDI3KlZrEfcEgcSnDDF1JpY1avFo9JdaLVhFWOEUQmh1nPsnqFLq3L5/Y4pQLF5W97u5O/75lwfn9PTWgRACH5BAkAAA4ALAsABwAPABgAAARj0DkAmryNXql339k2WV5YAt7HfRkqThVHvo7p0tyUUje8BkBgRwMAMhiBo1BXTB4OjCcy4CpGDwSslDoxSqFbavMKDlOCR2Q6eA663+23PC53o5pGJZtTt1/wcyJ0Yjg8Kg4RACH5BAkAAA4ALAoADAAPABcAAARa0EkJap3Y1cD5xQDHMMHoTWF5HMxKBgClHgTtwprosjectrveRmQavXydpBK5XA6byViKeMTloCfN1BnTaJWXbldrQVEyaCl6XV6jLOM03BA3hwGGNX3cfncjACH5BAkAAA4ALAIADQAfABAAAARh0MlJJ7i36q1v+F/GjdbHMMEZkiNgHgcDowHAYpQrHwQ/1zmRAyNypWaxH3BIHEpwwxdSaWNWrxaPSXWi1YRVjhFEJodZz7J6hS6ty+f2OKUCxeVve7uTv++ZcH5/T01oEQAh+QQJAAAOACwLAAcADwAYAAAEY9A5AJq8jV6pd9/ZNlleWALex30ZKk4VR76O6dLclFI3vAZAYEcDADIYgaNQV0weDownMuAqRg8ErJQ6MUqhW2rzCg5TgkdkOngOut/ttzwud6OaRiWbU7df8HMidGI4PCoOEQAh+QQJAAAOACwKAAwADwAXAAAEWtBJCWqd2NXA+cUAxzDB6E1heRzMSgYApR4E7cKa6LI3nLa73kZkGr18naQSuVwOm8lYinjE5aAnzdQZ02iVl25Xa0FRMmgpel1eoyzjNNwQN4cBhjV93H53IwAh+QQJAAAOACwCAA0AHwAQAAAEYdDJSSe4t+qtb/hfxo3WxzDBGZIjYB4HA6MBwGKUKx8EP9c5kQMjcqVmsR9wSBxKcMMXUmljVq8Wj0l1otWEVY4RRCaHWc+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 a24f53dbc..1d4b151c9 100644 --- a/Examples/_shared/GitHubAPI.swift +++ b/Examples/_shared/GitHubAPI.swift @@ -44,9 +44,8 @@ extension GitHub: TargetType { return "/users/\(name.urlEscaped)/repos" } } - public var method: Moya.Method { - .get - } + public var method: Moya.Method { .get } + public var task: Task { switch self { case .userRepositories: @@ -73,9 +72,8 @@ extension GitHub: TargetType { return "[{\"name\": \"\(name)\"}]".data(using: String.Encoding.utf8)! } } - public var headers: [String: String]? { - nil - } + public var headers: [String: String]? { nil } + } public func url(_ route: TargetType) -> String { diff --git a/Examples/_shared/GitHubUserContentAPI.swift b/Examples/_shared/GitHubUserContentAPI.swift index ec9af98db..6f93a0a51 100644 --- a/Examples/_shared/GitHubUserContentAPI.swift +++ b/Examples/_shared/GitHubUserContentAPI.swift @@ -33,9 +33,8 @@ extension GitHubUserContent: TargetType { return Giphy.animatedBirdData } } - public var headers: [String: String]? { - nil - } + public var headers: [String: String]? { nil } + } private let defaultDownloadDestination: DownloadDestination = { temporaryURL, response in diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index ce391f0ea..10759cecf 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -182,14 +182,10 @@ 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 { - .never - } + final class func neverStub(_: Target) -> Moya.StubBehavior { .never } /// Return a response immediately. - final class func immediatelyStub(_: Target) -> Moya.StubBehavior { - .immediate - } + final class func immediatelyStub(_: Target) -> Moya.StubBehavior { .immediate } /// Return a response after a delay. final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { { _ in .delayed(seconds: seconds) } diff --git a/Sources/Moya/MultiTarget.swift b/Sources/Moya/MultiTarget.swift index a8120da93..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 { - target.path - } + public var path: String { target.path } /// The baseURL of the embedded target. - public var baseURL: URL { - target.baseURL - } + public var baseURL: URL { target.baseURL } /// The HTTP method of the embedded target. - public var method: Moya.Method { - target.method - } + public var method: Moya.Method { target.method } /// The sampleData of the embedded target. - public var sampleData: Data { - target.sampleData - } + public var sampleData: Data { target.sampleData } /// The `Task` of the embedded target. - public var task: Task { - target.task - } + public var task: Task { target.task } /// The `ValidationType` of the embedded target. - public var validationType: ValidationType { - target.validationType - } + public var validationType: ValidationType { target.validationType } /// The headers of the embedded target. - public var headers: [String: String]? { - target.headers - } + public var headers: [String: String]? { target.headers } /// The embedded `TargetType`. public var target: TargetType { diff --git a/Sources/Moya/Response.swift b/Sources/Moya/Response.swift index 84398b605..a52167731 100644 --- a/Sources/Moya/Response.swift +++ b/Sources/Moya/Response.swift @@ -28,9 +28,7 @@ public final class Response: CustomDebugStringConvertible, Equatable { } /// A text description of the `Response`. Suitable for debugging. - public var debugDescription: String { - description - } + public var debugDescription: String { description } public static func == (lhs: Response, rhs: Response) -> Bool { lhs.statusCode == rhs.statusCode diff --git a/Sources/Moya/TargetType.swift b/Sources/Moya/TargetType.swift index 16251fb0c..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 { - .none - } + var validationType: ValidationType { .none } } diff --git a/Tests/MoyaTests/TestHelpers.swift b/Tests/MoyaTests/TestHelpers.swift index 1175506fd..67ecb8afa 100644 --- a/Tests/MoyaTests/TestHelpers.swift +++ b/Tests/MoyaTests/TestHelpers.swift @@ -41,13 +41,9 @@ extension GitHub: TargetType { } } - var validationType: ValidationType { - .successAndRedirectCodes - } + var validationType: ValidationType { .successAndRedirectCodes } - var headers: [String: String]? { - nil - } + var headers: [String: String]? { nil } } extension GitHub: Equatable { @@ -124,9 +120,7 @@ enum HTTPBin: TargetType, AccessTokenAuthorizable { } } - var headers: [String: String]? { - nil - } + var headers: [String: String]? { nil } var validationType: ValidationType { switch self { @@ -190,9 +184,7 @@ extension GitHubUserContent: TargetType { } } - public var headers: [String: String]? { - nil - } + public var headers: [String: String]? { nil } } // MARK: - Upload Multipart Helpers From 53598c155ddc30cf9c63764061a7700191261981 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Sat, 22 Feb 2020 09:53:35 -0300 Subject: [PATCH 15/21] Test carthage bootstrap without cache --- .circleci/config.yml | 2 +- docs/Examples/Basic.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ebf5535ac..3150efc2d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -61,7 +61,7 @@ jobs: BUNDLE_RETRY: 3 - run: name: Bootstrap Carthage - command: scripts/bootstrap-if-needed.sh + command: scripts/bootstrap.sh - save_cache: key: v{{ .Environment.CACHE_VERSION }}-dep-{{ checksum "Cartfile.resolved" }} paths: diff --git a/docs/Examples/Basic.md b/docs/Examples/Basic.md index f24f55005..7000167fa 100644 --- a/docs/Examples/Basic.md +++ b/docs/Examples/Basic.md @@ -163,7 +163,7 @@ var provider: MoyaProvider! let provider = MoyaProvider(endpointClosure: endpointClosure) ``` -Neato. Now how do we make a request? +Neat. Now how do we make a request? ```swift provider.request(.zen) { result in From 817865327b871579174ac1af3ef03c2df931d5c7 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Sat, 22 Feb 2020 13:04:31 -0300 Subject: [PATCH 16/21] Revert build script --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 3150efc2d..ebf5535ac 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -61,7 +61,7 @@ jobs: BUNDLE_RETRY: 3 - run: name: Bootstrap Carthage - command: scripts/bootstrap.sh + command: scripts/bootstrap-if-needed.sh - save_cache: key: v{{ .Environment.CACHE_VERSION }}-dep-{{ checksum "Cartfile.resolved" }} paths: From 6a562b0dc3123410c8981628583420180f27c57d Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Mon, 24 Feb 2020 23:39:03 -0300 Subject: [PATCH 17/21] Use shorten form of functions in reactive code. --- Sources/ReactiveMoya/MoyaProvider+Reactive.swift | 6 +----- Sources/RxMoya/MoyaProvider+Rx.swift | 5 +---- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift index 38e5d6f3b..4a525d6ab 100644 --- a/Sources/ReactiveMoya/MoyaProvider+Reactive.swift +++ b/Sources/ReactiveMoya/MoyaProvider+Reactive.swift @@ -29,11 +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 { 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/RxMoya/MoyaProvider+Rx.swift b/Sources/RxMoya/MoyaProvider+Rx.swift index d1b0429a2..7f91545bd 100644 --- a/Sources/RxMoya/MoyaProvider+Rx.swift +++ b/Sources/RxMoya/MoyaProvider+Rx.swift @@ -33,11 +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 { 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 { From dd8b6a6f4129206b30856824ccaf0c1be807c09b Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Tue, 25 Feb 2020 11:23:18 -0300 Subject: [PATCH 18/21] Addressing PR comments --- Sources/Moya/Plugins/NetworkLoggerPlugin.swift | 2 +- Tests/MoyaTests/MoyaProviderIntegrationTests.swift | 6 +++--- docs/Examples/Assets.md | 14 ++++---------- docs/Examples/Basic.md | 2 +- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Sources/Moya/Plugins/NetworkLoggerPlugin.swift b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift index d9a795226..06099c9ee 100644 --- a/Sources/Moya/Plugins/NetworkLoggerPlugin.swift +++ b/Sources/Moya/Plugins/NetworkLoggerPlugin.swift @@ -219,7 +219,7 @@ public extension NetworkLoggerPlugin.Configuration { // MARK: Defaults public static func defaultDataFormatter(_ data: Data) -> String { - String(decoding: data, as: UTF8.self) + return String(data: data, encoding: .utf8) ?? "## Cannot map data to String ##" } public static func defaultEntryFormatter(identifier: String, message: String, target: TargetType) -> String { diff --git a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift index 7738438be..ba47c4013 100644 --- a/Tests/MoyaTests/MoyaProviderIntegrationTests.swift +++ b/Tests/MoyaTests/MoyaProviderIntegrationTests.swift @@ -120,18 +120,18 @@ final class MoyaProviderIntegrationTests: QuickSpec { it("uses a background queue") { - let isMainThread = Atomic(wrappedValue: nil) + 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.wrappedValue = Thread.isMainThread + callbackQueueLabel.wrappedValue = DispatchQueue.currentLabel done() } } - expect(isMainThread.wrappedValue) == false + expect(callbackQueueLabel.wrappedValue) == "background_queue" } it("uses the main queue") { diff --git a/docs/Examples/Assets.md b/docs/Examples/Assets.md index 1f58747ab..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 { - assetDir.appendingPathComponent(assetName) - } + var localLocation: URL { assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - { _, _ in (self.localLocation, .removePreviousFile) } + return { _, _ in (self.localLocation, .removePreviousFile) } } - var task: Task { - .downloadDestination(downloadDestination) - } + var task: Task { .downloadDestination(downloadDestination) } /* Rest of TargetType diff --git a/docs/Examples/Basic.md b/docs/Examples/Basic.md index 7000167fa..f24f55005 100644 --- a/docs/Examples/Basic.md +++ b/docs/Examples/Basic.md @@ -163,7 +163,7 @@ var provider: MoyaProvider! let provider = MoyaProvider(endpointClosure: endpointClosure) ``` -Neat. Now how do we make a request? +Neato. Now how do we make a request? ```swift provider.request(.zen) { result in From f05a692a93bcd3d3675df52fe2e0f254d92b0875 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Tue, 25 Feb 2020 11:31:28 -0300 Subject: [PATCH 19/21] Couple more cleanups --- Sources/Moya/MoyaProvider+Internal.swift | 6 +++--- Sources/Moya/MoyaProvider.swift | 4 +--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/Sources/Moya/MoyaProvider+Internal.swift b/Sources/Moya/MoyaProvider+Internal.swift index 0f37f132b..53f9d1c33 100644 --- a/Sources/Moya/MoyaProvider+Internal.swift +++ b/Sources/Moya/MoyaProvider+Internal.swift @@ -158,9 +158,9 @@ public extension MoyaProvider { private extension MoyaProvider { private func interceptor(target: Target) -> MoyaRequestInterceptor { - MoyaRequestInterceptor(prepare: { [weak self] urlRequest in - self?.plugins.reduce(urlRequest) { $1.prepare($0, target: target) } ?? urlRequest - }) + 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 10759cecf..4b470a69a 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 { - response != nil - } + public var completed: Bool { response != nil } } /// A protocol representing a minimal interface for a MoyaProvider. From 6d9dce7c41631f12960cdd4d6c05ed98584d29ab Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Tue, 25 Feb 2020 12:58:25 -0300 Subject: [PATCH 20/21] Couple of more cleanups --- Sources/Moya/RequestTypeWrapper.swift | 8 +--- Tests/MoyaTests/NetworkLoggerPluginSpec.swift | 40 +++++-------------- Tests/MoyaTests/RxTestHelpers.swift | 8 +--- Tests/MoyaTests/TestHelpers.swift | 12 ++---- docs/Examples/Basic.md | 4 +- docs_CN/Examples/Assets.md | 14 ++----- 6 files changed, 22 insertions(+), 64 deletions(-) diff --git a/Sources/Moya/RequestTypeWrapper.swift b/Sources/Moya/RequestTypeWrapper.swift index 07d3ca832..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? { - _urlRequest - } + var request: URLRequest? { _urlRequest } - var sessionHeaders: [String: String] { - _request.sessionHeaders - } + var sessionHeaders: [String: String] { _request.sessionHeaders } private var _request: Request private var _urlRequest: URLRequest? diff --git a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift index 462e55c98..6b10ae615 100644 --- a/Tests/MoyaTests/NetworkLoggerPluginSpec.swift +++ b/Tests/MoyaTests/NetworkLoggerPluginSpec.swift @@ -164,13 +164,9 @@ private class TestStreamRequest: RequestType { ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") @@ -191,13 +187,9 @@ private class TestBodyRequest: RequestType { ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") @@ -218,13 +210,9 @@ private class TestCurlBodyRequest: RequestType { ["Content-Type": "application/badJson", "Accept-Language": "en-US"] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - 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? { - nil - } + var request: URLRequest? { nil } - var sessionHeaders: [String: String] { - [:] - } + var sessionHeaders: [String: String] { [:] } - func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { - self - } + func authenticate(username user: String, password: String, persistence: URLCredential.Persistence) -> Self { self } - func authenticate(with credential: URLCredential) -> Self { - self - } + func authenticate(with credential: URLCredential) -> Self { self } func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { handler("") diff --git a/Tests/MoyaTests/RxTestHelpers.swift b/Tests/MoyaTests/RxTestHelpers.swift index 5b751ebc9..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 { - Observable.just(self) - } + func asObservable() -> Observable { Observable.just(self) } - func asSingle() -> Single { - Single.just(self) - } + func asSingle() -> Single { Single.just(self) } } diff --git a/Tests/MoyaTests/TestHelpers.swift b/Tests/MoyaTests/TestHelpers.swift index 67ecb8afa..9ca48fdb1 100644 --- a/Tests/MoyaTests/TestHelpers.swift +++ b/Tests/MoyaTests/TestHelpers.swift @@ -24,13 +24,9 @@ extension GitHub: TargetType { } } - var method: Moya.Method { - .get - } + var method: Moya.Method { .get } - var task: Task { - .requestPlain - } + var task: Task { .requestPlain } var sampleData: Data { switch self { @@ -166,9 +162,7 @@ extension GitHubUserContent: TargetType { return nil } } - public var parameterEncoding: ParameterEncoding { - URLEncoding.default - } + public var parameterEncoding: ParameterEncoding { URLEncoding.default } public var task: Task { switch self { case .downloadMoyaWebContent: diff --git a/docs/Examples/Basic.md b/docs/Examples/Basic.md index f24f55005..416c72018 100644 --- a/docs/Examples/Basic.md +++ b/docs/Examples/Basic.md @@ -80,9 +80,7 @@ private extension String { addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } - var utf8Encoded: Data { - Data(self.utf8) - } + var utf8Encoded: Data { Data(self.utf8) } } ``` diff --git a/docs_CN/Examples/Assets.md b/docs_CN/Examples/Assets.md index 34501c70e..d60316503 100644 --- a/docs_CN/Examples/Assets.md +++ b/docs_CN/Examples/Assets.md @@ -22,21 +22,15 @@ enum Asset: TargetType { } } - var path: String { - "/assets/" + assetName - } + var path: String { "/assets/" + assetName } - var localLocation: URL { - assetDir.appendingPathComponent(assetName) - } + var localLocation: URL { assetDir.appendingPathComponent(assetName) } var downloadDestination: DownloadDestination { - { _, _ in (self.localLocation, .removePreviousFile) } + return { _, _ in (self.localLocation, .removePreviousFile) } } - var task: Task { - .downloadDestination(downloadDestination) - } + var task: Task { .downloadDestination(downloadDestination) } /* Rest of TargetType From d3206d70642443279313de7308d790c58f765823 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Wed, 26 Feb 2020 23:27:23 -0300 Subject: [PATCH 21/21] Updating more returns that will be better explicity --- Sources/Moya/MoyaProvider+Internal.swift | 2 +- Sources/Moya/MoyaProvider.swift | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/Moya/MoyaProvider+Internal.swift b/Sources/Moya/MoyaProvider+Internal.swift index 53f9d1c33..070fae8c6 100644 --- a/Sources/Moya/MoyaProvider+Internal.swift +++ b/Sources/Moya/MoyaProvider+Internal.swift @@ -105,7 +105,7 @@ public extension MoyaProvider { /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint, plugins: [PluginType], request: URLRequest) -> (() -> Void) { // swiftlint:disable:this function_parameter_count - { + return { if token.isCancelled { self.cancelCompletion(completion, target: target) return diff --git a/Sources/Moya/MoyaProvider.swift b/Sources/Moya/MoyaProvider.swift index 4b470a69a..a2fef1da4 100755 --- a/Sources/Moya/MoyaProvider.swift +++ b/Sources/Moya/MoyaProvider.swift @@ -186,7 +186,8 @@ public extension MoyaProvider { final class func immediatelyStub(_: Target) -> Moya.StubBehavior { .immediate } /// Return a response after a delay. - final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { { _ in .delayed(seconds: seconds) } + final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior { + return { _ in .delayed(seconds: seconds) } } }