From 2b5c56a5ee494b603979e953a2899d05cdece98d Mon Sep 17 00:00:00 2001 From: Miguel Torres Date: Fri, 30 Sep 2022 14:27:42 +0200 Subject: [PATCH] fix(swiftformat): executed "swiftformat ." --- Example/Harmony/AppDelegate.swift | 39 ++++-- .../Harmony/Core/ApplicationProvider.swift | 8 +- .../Item/Data/ItemNetworkDataSource.swift | 16 +-- .../Item/Domain/Mappers/ItemMapper.swift | 8 +- .../Domain/Presenters/ItemListPresenter.swift | 2 +- .../Core/Features/Item/ItemProvider.swift | 18 +-- ...UnauthorizedStatusCodeRequestRetrier.swift | 2 +- .../SwiftUI/ItemDetail/ItemDetailView.swift | 14 +- .../SwiftUI/ItemList/ItemListView.swift | 6 +- .../SwiftUI/ItemList/ItemListViewState.swift | 5 +- .../Screens/SwiftUI/Splash/SplashView.swift | 3 +- .../ItemDetail/ItemDetailViewController.swift | 11 +- .../Screens/UIKit/ItemList/ItemCell.swift | 11 +- .../ItemList/ItemListViewController.swift | 15 +- .../UIKit/Splash/SplashViewController.swift | 4 +- Example/Harmony/Utils/Alamofire+Future.swift | 34 +++-- .../Harmony/Utils/BaseURLRequestAdapter.swift | 26 +++- .../Utils/ContainerViewController.swift | 75 +++++----- Example/Harmony/Utils/LazyView.swift | 1 + .../Harmony/Utils/MultiRequestAdapter.swift | 9 +- .../Utils/URLLoggerRequestAdapter.swift | 13 +- Example/Tests/Future+DeallocTests.swift | 2 - Example/Tests/Future+InitTests.swift | 21 ++- Example/Tests/Future+SetTests.swift | 17 ++- Example/Tests/Future+ThenTests.swift | 26 ++-- .../Performance/FuturePerformanceTests.swift | 3 +- .../Performance/GCDPerformanceTests.swift | 7 +- .../Performance/PromisesPerformanceTest.swift | 5 +- Example/Tests/TestHelper.swift | 5 +- Package.swift | 6 +- Sources/Harmony/Common/Error/ClassError.swift | 1 - Sources/Harmony/Common/Error/CoreError.swift | 16 +-- .../Harmony/Common/Error/ErrorHelper.swift | 2 +- .../Common/Extensions/Data+Extensions.swift | 39 +++--- .../Common/Extensions/JSONDecoding.swift | 17 ++- .../Common/Extensions/Number+Extensions.swift | 24 ++-- .../Common/Extensions/String+Extensions.swift | 92 ++++++++++--- .../Common/JSON/CodingKeyStrategies.swift | 10 +- .../Common/JSON/MutableCodingKey.swift | 3 +- Sources/Harmony/Common/KeyValueObserver.swift | 12 +- Sources/Harmony/Common/LinkRecognizer.swift | 53 ++++--- .../Common/Logger/DeviceConsoleLogger.swift | 5 +- Sources/Harmony/Common/Logger/Logger.swift | 21 ++- .../Harmony/Common/ScopeLock/ScopeLock.swift | 15 +- .../Data/DataSource/AnyDataSource.swift | 27 ++-- .../Data/DataSource/AnyGetDataSource.swift | 22 +-- .../Data/DataSource/AnyPutDataSource.swift | 22 +-- .../Harmony/Data/DataSource/DataSource.swift | 40 +++--- .../Data/DataSource/DataSourceAssembler.swift | 38 ++--- .../Data/DataSource/DataSourceValidator.swift | 5 +- .../Data/DataSource/DebugDataSource.swift | 23 ++-- .../DataSource/DeviceStorageDataSource.swift | 28 ++-- .../FileSystemStorageDataSource.swift | 65 ++++++--- .../Data/DataSource/InMemoryDataSource.swift | 9 +- .../Data/DataSource/RetryDataSource.swift | 36 ++--- .../DataSource/TimedCacheDataSource.swift | 28 ++-- .../Data/DataSource/VoidDataSource.swift | 32 ++--- .../Data/Mapper/DataSourceMapper.swift | 35 +++-- .../Harmony/Data/Mapper/Mapper+Codable.swift | 13 +- .../Harmony/Data/Mapper/Mapper+NSCoding.swift | 8 +- Sources/Harmony/Data/Mapper/Mapper.swift | 72 +++++----- .../Harmony/Data/Operation/Operation.swift | 7 +- Sources/Harmony/Data/Query/Query.swift | 25 ++-- .../Data/Repository/AnyGetRepository.swift | 23 ++-- .../Data/Repository/AnyPutRepository.swift | 23 ++-- .../Data/Repository/AnyRepository.swift | 28 ++-- .../Data/Repository/CacheRepository.swift | 33 +++-- .../Harmony/Data/Repository/Repository.swift | 41 +++--- .../Data/Repository/RepositoryAssembler.swift | 38 ++--- .../Data/Repository/RepositoryMapper.swift | 33 +++-- .../Data/Repository/RetryRepository.swift | 14 +- .../SingleDataSourceRepository.swift | 42 +++--- .../Data/Repository/VoidRepository.swift | 42 +++--- .../Data/Validator/ObjectValidation.swift | 3 +- .../VastraReachabilityStrategy.swift | 2 +- .../Data/Validator/VastraService.swift | 5 +- .../Data/Validator/VastraStrategy.swift | 1 - .../Validator/VastraTimestampStrategy.swift | 11 +- .../Domain/Interactor/Interactor.swift | 2 +- .../Domain/Interactor/InteractorDelete.swift | 42 +++--- .../Domain/Interactor/InteractorGet.swift | 51 ++++--- .../Domain/Interactor/InteractorPut.swift | 62 ++++++--- .../Executor/Collections+Executor.swift | 31 ++--- .../Future/Executor/DirectExecutor.swift | 31 +++-- .../Executor/DispatchQueueExecutor.swift | 5 +- .../Harmony/Future/Executor/Executor.swift | 16 ++- .../Future/Executor/ExecutorFactory.swift | 7 +- .../Executor/OperationQueueExecutor.swift | 7 +- .../Future/Future/Executor+Future.swift | 13 +- .../Harmony/Future/Future/Future+Batch.swift | 53 +++---- .../Future/Future/Future+Extensions.swift | 2 +- .../Future/Future/Future+Functional.swift | 34 ++--- .../Future/Future/Future+Operators.swift | 7 +- .../Future/Future/Future+Optionals.swift | 12 +- .../Harmony/Future/Future/Future+Time.swift | 7 +- Sources/Harmony/Future/Future/Future.swift | 112 ++++++++------- .../Future/Observable/Observable+Batch.swift | 47 ++++--- .../Observable/Observable+Extensions.swift | 2 +- .../Observable/Observable+Functional.swift | 30 ++-- .../Observable/Observable+Optionals.swift | 12 +- .../Future/Observable/Observable+Time.swift | 5 +- .../Future/Observable/Observable.swift | 86 ++++++------ .../Future/Observable/ObservableHub.swift | 13 +- .../Harmony/Security/KeychainDataSource.swift | 33 +++-- .../Security/KeychainGetInteractor.swift | 4 +- .../Harmony/Security/KeychainService.swift | 40 ++++-- .../Security/KeychainSetInteractor.swift | 11 +- Sources/Harmony/Security/SecureKey.swift | 37 +++-- .../HarmonyTesting/Data/DataSourceSpy.swift | 13 +- .../Data/MockObjectValidation.swift | 4 +- .../HarmonyTesting/Data/RepositorySpy.swift | 20 ++- .../Interactor/MockInteractorDelete.swift | 123 ++++++++++------- .../Interactor/MockInteractorGet.swift | 98 ++++++------- .../Interactor/MockInteractorPut.swift | 130 ++++++++++-------- .../ObjectMother/BoolObjectMother.swift | 2 +- .../ObjectMother/DoubleObjectMother.swift | 2 +- .../ObjectMother/IntegerObjectModel.swift | 2 +- Sources/HarmonyTesting/TestUtils.swift | 4 +- Tests/HarmonyTests/CacheRepositoryTests.swift | 5 +- .../DelayedMainQueueExecutorTests.swift | 5 +- .../DeviceStorageDataSourcePrefixTests.swift | 7 +- .../DeviceStorageDataSourceRegularTests.swift | 6 +- .../DeviceStorageDataSourceRootKeyTests.swift | 7 +- .../DeviceStorageDataSourceTester.swift | 26 +++- .../FileSystemStorageDataSourceTests.swift | 28 +++- Tests/HarmonyTests/FutureTests.swift | 17 ++- .../InMemoryDataSourceTests.swift | 5 +- .../TimedCacheDataSourceTests.swift | 5 +- 128 files changed, 1616 insertions(+), 1303 deletions(-) diff --git a/Example/Harmony/AppDelegate.swift b/Example/Harmony/AppDelegate.swift index bb3ec85b..9032f2ee 100644 --- a/Example/Harmony/AppDelegate.swift +++ b/Example/Harmony/AppDelegate.swift @@ -6,9 +6,9 @@ // Copyright (c) 2017 Mobile Jazz. All rights reserved. // -import UIKit import Harmony import SwiftUI +import UIKit let applicationComponent: ApplicationComponent = ApplicationDefaultModule() @@ -16,16 +16,17 @@ enum ApplicationUI { case UIKit case SwiftUI } + // Modify this property to change the UI implementation! let applicationUI: ApplicationUI = .SwiftUI @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? var observable: Observable! - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + func application(_: UIApplication, + didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { switch applicationUI { case .UIKit: let splash = SplashViewController() @@ -59,25 +60,33 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } - func applicationWillResignActive(_ application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + func applicationWillResignActive(_: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types + // of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the + // application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games + // should use this method to pause the game. } - func applicationDidEnterBackground(_ application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + func applicationDidEnterBackground(_: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough + // application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of + // applicationWillTerminate: when the user quits. } - func applicationWillEnterForeground(_ application: UIApplication) { - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + func applicationWillEnterForeground(_: UIApplication) { + // Called as part of the transition from the background to the inactive state; here you can undo many of the + // changes made on entering the background. } - func applicationDidBecomeActive(_ application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + func applicationDidBecomeActive(_: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application + // was previously in the background, optionally refresh the user interface. } - func applicationWillTerminate(_ application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + func applicationWillTerminate(_: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also + // applicationDidEnterBackground:. } } diff --git a/Example/Harmony/Core/ApplicationProvider.swift b/Example/Harmony/Core/ApplicationProvider.swift index ce52c5ea..36f9f4f9 100644 --- a/Example/Harmony/Core/ApplicationProvider.swift +++ b/Example/Harmony/Core/ApplicationProvider.swift @@ -6,8 +6,8 @@ // Copyright © 2021 CocoaPods. All rights reserved. // -import Harmony import Alamofire +import Harmony // Enabling vastra service as an object validation extension VastraService: ObjectValidation {} @@ -17,14 +17,14 @@ protocol ApplicationComponent { } class ApplicationDefaultModule: ApplicationComponent { - private lazy var logger: Logger = DeviceConsoleLogger() private lazy var backgroundExecutor: Executor = DispatchQueueExecutor() private lazy var apiClient: Session = { // Alamofire Session Manager - let sessionManager = Session(interceptor: BaseURLRequestAdapter(URL(string: "https://demo3068405.mockable.io")!, - [UnauthorizedStatusCodeRequestRetrier()])) + let sessionManager = + Session(interceptor: BaseURLRequestAdapter(URL(string: "https://demo3068405.mockable.io")!, + [UnauthorizedStatusCodeRequestRetrier()])) return sessionManager }() diff --git a/Example/Harmony/Core/Features/Item/Data/ItemNetworkDataSource.swift b/Example/Harmony/Core/Features/Item/Data/ItemNetworkDataSource.swift index 6299116b..6effe4c4 100644 --- a/Example/Harmony/Core/Features/Item/Data/ItemNetworkDataSource.swift +++ b/Example/Harmony/Core/Features/Item/Data/ItemNetworkDataSource.swift @@ -5,21 +5,20 @@ import Foundation -import Harmony import Alamofire +import Harmony -extension ItemEntity { - fileprivate static var fromNetworkMap: [String: String] { +private extension ItemEntity { + static var fromNetworkMap: [String: String] { return ["image-url": "imageURL"] } - fileprivate static var toNetworkMap: [String: String] { + static var toNetworkMap: [String: String] { return ["imageURL": "image-url"] } } class ItemNetworkDataSource: GetDataSource { - typealias T = ItemEntity var sessionManager: Session @@ -56,9 +55,10 @@ private extension ItemNetworkDataSource { guard let json = data as? [String: AnyObject] else { throw CoreError.NotFound() } - let future = json.decodeAs(ItemEntity.self, keyDecodingStrategy: .map(ItemEntity.fromNetworkMap)) { item in - item.lastUpdate = Date() - } + let future = json + .decodeAs(ItemEntity.self, keyDecodingStrategy: .map(ItemEntity.fromNetworkMap)) { item in + item.lastUpdate = Date() + } return future } } diff --git a/Example/Harmony/Core/Features/Item/Domain/Mappers/ItemMapper.swift b/Example/Harmony/Core/Features/Item/Domain/Mappers/ItemMapper.swift index b44006d4..ff21fc54 100644 --- a/Example/Harmony/Core/Features/Item/Domain/Mappers/ItemMapper.swift +++ b/Example/Harmony/Core/Features/Item/Domain/Mappers/ItemMapper.swift @@ -9,7 +9,13 @@ import Harmony class ItemToItemEntityMapper: Mapper { override func map(_ from: Item) throws -> ItemEntity { - return ItemEntity(id: from.id, name: from.name, price: from.price, count: from.count, imageURL: from.imageURL) + return ItemEntity( + id: from.id, + name: from.name, + price: from.price, + count: from.count, + imageURL: from.imageURL + ) } } diff --git a/Example/Harmony/Core/Features/Item/Domain/Presenters/ItemListPresenter.swift b/Example/Harmony/Core/Features/Item/Domain/Presenters/ItemListPresenter.swift index f62d3799..514a518a 100644 --- a/Example/Harmony/Core/Features/Item/Domain/Presenters/ItemListPresenter.swift +++ b/Example/Harmony/Core/Features/Item/Domain/Presenters/ItemListPresenter.swift @@ -48,7 +48,7 @@ class ItemListDefaultPresenter: ItemListPresenter { func onActionReloadList() { view?.onDisplayProgressHud(show: true) - self.getItems.execute(MainSyncOperation()).then { items in + getItems.execute(MainSyncOperation()).then { items in self.view?.onDisplayProgressHud(show: false) self.view?.onDisplayItems(items) }.fail { error in diff --git a/Example/Harmony/Core/Features/Item/ItemProvider.swift b/Example/Harmony/Core/Features/Item/ItemProvider.swift index e009a02f..0faba55e 100644 --- a/Example/Harmony/Core/Features/Item/ItemProvider.swift +++ b/Example/Harmony/Core/Features/Item/ItemProvider.swift @@ -6,8 +6,8 @@ // Copyright © 2021 CocoaPods. All rights reserved. // -import Harmony import Alamofire +import Harmony protocol ItemComponent { func itemListPresenter(view: ItemListPresenterView) -> ItemListPresenter @@ -30,18 +30,21 @@ class ItemDefaultModule: ItemComponent { // To debug the UI upon random API behavior, adding this intermediate layer let itemNetworkDataSource = DebugDataSource(DataSourceAssembler(get: baseDataSource), delay: .sync(0.5), - error: .error(CoreError.Failed("Debug Fail"), probability: 0.01), + error: .error( + CoreError.Failed("Debug Fail"), + probability: 0.01 + ), logger: DeviceConsoleLogger()) // Adding retry behavior in case of error let networkDataSource = RetryDataSource(itemNetworkDataSource, retryCount: 1) { error in - return error._code == NSURLErrorTimedOut && error._domain == NSURLErrorDomain + error._code == NSURLErrorTimedOut && error._domain == NSURLErrorDomain } return AnyDataSource(networkDataSource) }() private lazy var storageDataSource: AnyDataSource = { - return AnyDataSource( + AnyDataSource( DataSourceMapper(dataSource: self.storage, toInMapper: EncodableToDataMapper(), toOutMapper: DataToDecodableMapper()) @@ -49,7 +52,6 @@ class ItemDefaultModule: ItemComponent { }() private lazy var repository: AnyRepository = { - let vastra = VastraService([VastraTimestampStrategy()]) let storageValidationDataSource = DataSourceValidator(dataSource: self.storageDataSource, validator: vastra) @@ -64,11 +66,11 @@ class ItemDefaultModule: ItemComponent { }() private func getAllItemsInteractor() -> GetAllItemsInteractor { - return GetAllItemsInteractor(executor: self.executor, - getItems: Interactor.GetAllByQuery(DirectExecutor(), self.repository)) + return GetAllItemsInteractor(executor: executor, + getItems: Interactor.GetAllByQuery(DirectExecutor(), repository)) } func itemListPresenter(view: ItemListPresenterView) -> ItemListPresenter { - return ItemListDefaultPresenter(view, self.getAllItemsInteractor()) + return ItemListDefaultPresenter(view, getAllItemsInteractor()) } } diff --git a/Example/Harmony/Core/Features/NetworkUtils/UnauthorizedStatusCodeRequestRetrier.swift b/Example/Harmony/Core/Features/NetworkUtils/UnauthorizedStatusCodeRequestRetrier.swift index ac894c93..363560f4 100644 --- a/Example/Harmony/Core/Features/NetworkUtils/UnauthorizedStatusCodeRequestRetrier.swift +++ b/Example/Harmony/Core/Features/NetworkUtils/UnauthorizedStatusCodeRequestRetrier.swift @@ -11,7 +11,7 @@ import UIKit import Alamofire class UnauthorizedStatusCodeRequestRetrier: RequestRetrier { - func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { + func retry(_ request: Request, for _: Session, dueTo _: Error, completion: @escaping (RetryResult) -> Void) { if request.response?.statusCode == 401 { // TODO: Logout user } diff --git a/Example/Harmony/Screens/SwiftUI/ItemDetail/ItemDetailView.swift b/Example/Harmony/Screens/SwiftUI/ItemDetail/ItemDetailView.swift index 80706218..586ab828 100644 --- a/Example/Harmony/Screens/SwiftUI/ItemDetail/ItemDetailView.swift +++ b/Example/Harmony/Screens/SwiftUI/ItemDetail/ItemDetailView.swift @@ -6,8 +6,8 @@ // Copyright © 2017 Mobile Jazz. All rights reserved. // -import SwiftUI import Kingfisher +import SwiftUI struct ItemDetailView: View { var item: Item @@ -24,7 +24,7 @@ struct ItemDetailView: View { Spacer() Text("\(Int(item.price))€") .font(.system(size: 80, weight: .bold)) - .foregroundColor(Color(red: 0, green: 190.0/256.0, blue: 176.0/256.0)) + .foregroundColor(Color(red: 0, green: 190.0 / 256.0, blue: 176.0 / 256.0)) Spacer() }.navigationTitle(item.name) } @@ -33,7 +33,15 @@ struct ItemDetailView: View { struct ItemDetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { - ItemDetailView(item: Item(id: "1", name: "Macbook Pro", price: 1234.56, count: 12, imageURL: URL(string: "(https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/mbp-spacegray-select-202206_GEO_ES?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1654014007395"))) + ItemDetailView(item: Item( + id: "1", + name: "Macbook Pro", + price: 1234.56, + count: 12, + imageURL: URL( + string: "(https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/mbp-spacegray-select-202206_GEO_ES?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1654014007395" + ) + )) } } } diff --git a/Example/Harmony/Screens/SwiftUI/ItemList/ItemListView.swift b/Example/Harmony/Screens/SwiftUI/ItemList/ItemListView.swift index ea936133..5df242c3 100644 --- a/Example/Harmony/Screens/SwiftUI/ItemList/ItemListView.swift +++ b/Example/Harmony/Screens/SwiftUI/ItemList/ItemListView.swift @@ -6,11 +6,10 @@ // Copyright © 2022 CocoaPods. All rights reserved. // -import SwiftUI import Kingfisher +import SwiftUI struct ItemListView: View { - @StateObject var viewState: ItemListViewState var body: some View { @@ -52,7 +51,7 @@ struct ItemListView: View { Spacer() Text("\(Int(item.price))€") .font(.system(size: 23, weight: .bold)) - .foregroundColor(Color(red: 0, green: 190.0/256.0, blue: 176.0/256.0)) + .foregroundColor(Color(red: 0, green: 190.0 / 256.0, blue: 176.0 / 256.0)) } } } @@ -68,7 +67,6 @@ struct ItemListView: View { } label: { Image(systemName: "arrow.clockwise") } - } } } diff --git a/Example/Harmony/Screens/SwiftUI/ItemList/ItemListViewState.swift b/Example/Harmony/Screens/SwiftUI/ItemList/ItemListViewState.swift index de946b9d..f801f3ba 100644 --- a/Example/Harmony/Screens/SwiftUI/ItemList/ItemListViewState.swift +++ b/Example/Harmony/Screens/SwiftUI/ItemList/ItemListViewState.swift @@ -9,7 +9,6 @@ import Foundation class ItemListViewState: ObservableObject, ItemListPresenterView { - @Published var items: [Item] @Published var isLoading: Bool = true @Published var error: Error? @@ -23,12 +22,12 @@ class ItemListViewState: ObservableObject, ItemListPresenterView { lazy var presenter = applicationComponent.itemComponent.itemListPresenter(view: self) func onDisplayProgressHud(show: Bool) { - self.isLoading = show + isLoading = show } func onDisplayItems(_ items: [Item]) { self.items = items - self.error = nil + error = nil } func onNavigateToItem(_ item: Item) { diff --git a/Example/Harmony/Screens/SwiftUI/Splash/SplashView.swift b/Example/Harmony/Screens/SwiftUI/Splash/SplashView.swift index 280456c4..df7cabec 100644 --- a/Example/Harmony/Screens/SwiftUI/Splash/SplashView.swift +++ b/Example/Harmony/Screens/SwiftUI/Splash/SplashView.swift @@ -11,7 +11,7 @@ import SwiftUI struct SplashView: View { var body: some View { ZStack { - Color(red: 0, green: 190.0/256.0, blue: 176.0/256.0) + Color(red: 0, green: 190.0 / 256.0, blue: 176.0 / 256.0) .ignoresSafeArea() VStack { Text("Splash") @@ -20,7 +20,6 @@ struct SplashView: View { ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: Color.white)) } - } } } diff --git a/Example/Harmony/Screens/UIKit/ItemDetail/ItemDetailViewController.swift b/Example/Harmony/Screens/UIKit/ItemDetail/ItemDetailViewController.swift index 133ef48d..ad6520cc 100644 --- a/Example/Harmony/Screens/UIKit/ItemDetail/ItemDetailViewController.swift +++ b/Example/Harmony/Screens/UIKit/ItemDetail/ItemDetailViewController.swift @@ -9,11 +9,10 @@ import UIKit class ItemDetailViewController: UIViewController { - - @IBOutlet weak var imageView: UIImageView! - @IBOutlet weak var nameLabel: UILabel! - @IBOutlet weak var unitsLabel: UILabel! - @IBOutlet weak var priceLabel: UILabel! + @IBOutlet var imageView: UIImageView! + @IBOutlet var nameLabel: UILabel! + @IBOutlet var unitsLabel: UILabel! + @IBOutlet var priceLabel: UILabel! // Temp item to obtain it from previous screen. // This could be improved. @@ -23,7 +22,7 @@ class ItemDetailViewController: UIViewController { super.viewWillAppear(animated) if let item = item { - self.title = item.name + title = item.name nameLabel.text = item.name unitsLabel.text = "\(item.count) units" diff --git a/Example/Harmony/Screens/UIKit/ItemList/ItemCell.swift b/Example/Harmony/Screens/UIKit/ItemList/ItemCell.swift index b998ff19..928438f7 100644 --- a/Example/Harmony/Screens/UIKit/ItemList/ItemCell.swift +++ b/Example/Harmony/Screens/UIKit/ItemList/ItemCell.swift @@ -6,15 +6,14 @@ // Copyright © 2017 Mobile Jazz. All rights reserved. // -import UIKit import Kingfisher +import UIKit class ItemCell: UITableViewCell { - - @IBOutlet weak var itemImageView: UIImageView! - @IBOutlet weak var itemNameLabel: UILabel! - @IBOutlet weak var itemCountLabel: UILabel! - @IBOutlet weak var itemPriceLabel: UILabel! + @IBOutlet var itemImageView: UIImageView! + @IBOutlet var itemNameLabel: UILabel! + @IBOutlet var itemCountLabel: UILabel! + @IBOutlet var itemPriceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() diff --git a/Example/Harmony/Screens/UIKit/ItemList/ItemListViewController.swift b/Example/Harmony/Screens/UIKit/ItemList/ItemListViewController.swift index 95b6650c..4cb366d7 100644 --- a/Example/Harmony/Screens/UIKit/ItemList/ItemListViewController.swift +++ b/Example/Harmony/Screens/UIKit/ItemList/ItemListViewController.swift @@ -6,15 +6,14 @@ // Copyright © 2017 Mobile Jazz. All rights reserved. // -import UIKit import Harmony +import UIKit class ItemListViewController: UIViewController, ItemListPresenterView, UITableViewDataSource, UITableViewDelegate { - lazy var presenter = applicationComponent.itemComponent.itemListPresenter(view: self) - @IBOutlet weak var tableView: UITableView! - @IBOutlet weak var activityIndicator: UIActivityIndicatorView! + @IBOutlet var tableView: UITableView! + @IBOutlet var activityIndicator: UIActivityIndicatorView! private var items: [Item] = [] @@ -30,7 +29,7 @@ class ItemListViewController: UIViewController, ItemListPresenterView, UITableVi tableView.estimatedRowHeight = 68 } - @IBAction func reloadButtonAction(_ sender: Any) { + @IBAction func reloadButtonAction(_: Any) { presenter.onActionReloadList() } @@ -74,11 +73,11 @@ class ItemListViewController: UIViewController, ItemListPresenterView, UITableVi // MARK: UITableViewDataSource - func numberOfSections(in tableView: UITableView) -> Int { + func numberOfSections(in _: UITableView) -> Int { return 1 } - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return items.count } @@ -102,7 +101,7 @@ class ItemListViewController: UIViewController, ItemListPresenterView, UITableVi // MARK: UITableViewDelegate - func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { presenter.onActionSelected(item: items[indexPath.row]) } } diff --git a/Example/Harmony/Screens/UIKit/Splash/SplashViewController.swift b/Example/Harmony/Screens/UIKit/Splash/SplashViewController.swift index c0261620..dfc963a5 100644 --- a/Example/Harmony/Screens/UIKit/Splash/SplashViewController.swift +++ b/Example/Harmony/Screens/UIKit/Splash/SplashViewController.swift @@ -8,6 +8,4 @@ import UIKit -class SplashViewController: UIViewController { - -} +class SplashViewController: UIViewController {} diff --git a/Example/Harmony/Utils/Alamofire+Future.swift b/Example/Harmony/Utils/Alamofire+Future.swift index 3f47efe4..18f83b44 100644 --- a/Example/Harmony/Utils/Alamofire+Future.swift +++ b/Example/Harmony/Utils/Alamofire+Future.swift @@ -14,8 +14,8 @@ // limitations under the License. // -import Foundation import Alamofire +import Foundation import Harmony public enum HarmonyAlamofireError: Error { @@ -24,23 +24,27 @@ public enum HarmonyAlamofireError: Error { public extension DataRequest { /// Inserts the JSON data response into a Future with a mapping window - func then(queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - success: @escaping (Any) throws -> T, - failure: @escaping (Error, HTTPURLResponse?, Data?) -> Error = { (error, _, _) in error }) -> Future { + func then( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + success: @escaping (Any) throws -> T, + failure: @escaping (Error, HTTPURLResponse?, Data?) -> Error = { error, _, _ in error } + ) -> Future { return Future { resolver in - self.validate().response(queue: queue ?? .main, responseSerializer: JSONResponseSerializer(options: options)) { response in - switch response.result { - case .failure(let error): - resolver.set(failure(error, response.response, response.data)) - case .success(let data): - do { - resolver.set(try success(data)) - } catch let error { - resolver.set(error) + self.validate() + .response(queue: queue ?? .main, + responseSerializer: JSONResponseSerializer(options: options)) { response in + switch response.result { + case let .failure(error): + resolver.set(failure(error, response.response, response.data)) + case let .success(data): + do { + resolver.set(try success(data)) + } catch { + resolver.set(error) + } } } - } } } diff --git a/Example/Harmony/Utils/BaseURLRequestAdapter.swift b/Example/Harmony/Utils/BaseURLRequestAdapter.swift index 6e826dd5..c874f815 100644 --- a/Example/Harmony/Utils/BaseURLRequestAdapter.swift +++ b/Example/Harmony/Utils/BaseURLRequestAdapter.swift @@ -14,11 +14,10 @@ // limitations under the License. // -import Foundation import Alamofire +import Foundation public class BaseURLRequestAdapter: RequestInterceptor { - // Example of usage of a bearer token public let baseURL: URL private var retriers: [RequestRetrier] = [] @@ -28,7 +27,11 @@ public class BaseURLRequestAdapter: RequestInterceptor { self.retriers = retriers } - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + public func adapt( + _ urlRequest: URLRequest, + for _: Session, + completion: @escaping (Result) -> Void + ) { guard let incomingURL = urlRequest.url else { completion(.success(urlRequest)) return @@ -55,11 +58,22 @@ public class BaseURLRequestAdapter: RequestInterceptor { completion(.success(request)) } - public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { + public func retry( + _ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void + ) { should(0, session, retry: request, with: error, completion: completion) } - private func should(_ index: Int, _ manager: Session, retry request: Request, with error: Error, completion: @escaping (RetryResult) -> Void) { + private func should( + _ index: Int, + _ manager: Session, + retry request: Request, + with error: Error, + completion: @escaping (RetryResult) -> Void + ) { if index < retriers.count { let retrier = retriers[index] retrier.retry(request, for: manager, dueTo: error) { retryResult in @@ -67,7 +81,7 @@ public class BaseURLRequestAdapter: RequestInterceptor { case .retry, .retryWithDelay, .doNotRetry: completion(retryResult) case .doNotRetryWithError: - self.should(index+1, manager, retry: request, with: error, completion: completion) + self.should(index + 1, manager, retry: request, with: error, completion: completion) } } } else { diff --git a/Example/Harmony/Utils/ContainerViewController.swift b/Example/Harmony/Utils/ContainerViewController.swift index 1b3b316d..eab735b1 100644 --- a/Example/Harmony/Utils/ContainerViewController.swift +++ b/Example/Harmony/Utils/ContainerViewController.swift @@ -23,9 +23,8 @@ import UIKit /// Typically used as the window's rootViewController. /// public class ContainerViewController: UIViewController { - private static let animationDuration: Double = 0.40 - private static let animationOptions = UIView.AnimationOptions(rawValue: (7<<16)) + private static let animationOptions = UIView.AnimationOptions(rawValue: 7 << 16) public enum Animation { case none @@ -46,7 +45,7 @@ public class ContainerViewController: UIViewController { } public required init?(coder aDecoder: NSCoder) { - self.viewController = UIViewController(nibName: nil, bundle: nil) + viewController = UIViewController(nibName: nil, bundle: nil) super.init(coder: aDecoder) } @@ -64,63 +63,63 @@ public class ContainerViewController: UIViewController { // Configuring the new view controller's view let subview = viewController.view! subview.autoresizingMask = [.flexibleWidth, .flexibleHeight] - subview.frame = self.view.bounds + subview.frame = view.bounds // Storing the new view controller self.viewController = viewController oldVC.willMove(toParent: nil) - self.addChild(newVC) + addChild(newVC) switch animation { case .none: oldVC.view.removeFromSuperview() - self.view.insertSubview(newVC.view, at: 0) + view.insertSubview(newVC.view, at: 0) oldVC.removeFromParent() newVC.didMove(toParent: self) case .crossDisolve: - self.view.insertSubview(newVC.view, belowSubview: oldVC.view) + view.insertSubview(newVC.view, belowSubview: oldVC.view) UIView.animate(withDuration: ContainerViewController.animationDuration, delay: 0, options: ContainerViewController.animationOptions, animations: { - oldVC.view.alpha = 0.0 + oldVC.view.alpha = 0.0 }, - completion: { (_) in - oldVC.view.removeFromSuperview() - oldVC.removeFromParent() - newVC.didMove(toParent: self) + completion: { _ in + oldVC.view.removeFromSuperview() + oldVC.removeFromParent() + newVC.didMove(toParent: self) }) case .newModalBottom: newVC.view.alpha = 0.0 - newVC.view.frame = self.view.bounds.offsetBy(dx: 0, dy: UIScreen.main.bounds.size.height) - self.view.insertSubview(newVC.view, aboveSubview: oldVC.view) + newVC.view.frame = view.bounds.offsetBy(dx: 0, dy: UIScreen.main.bounds.size.height) + view.insertSubview(newVC.view, aboveSubview: oldVC.view) UIView.animate(withDuration: ContainerViewController.animationDuration, delay: 0, options: ContainerViewController.animationOptions, animations: { - newVC.view.alpha = 1.0 - newVC.view.frame = self.view.bounds + newVC.view.alpha = 1.0 + newVC.view.frame = self.view.bounds }, - completion: { (_) in - oldVC.view.removeFromSuperview() - oldVC.removeFromParent() - newVC.didMove(toParent: self) + completion: { _ in + oldVC.view.removeFromSuperview() + oldVC.removeFromParent() + newVC.didMove(toParent: self) }) case .oldModalBottom: - let frame = self.view.bounds.offsetBy(dx: 0, dy: UIScreen.main.bounds.size.height) - self.view.insertSubview(newVC.view, belowSubview: oldVC.view) + let frame = view.bounds.offsetBy(dx: 0, dy: UIScreen.main.bounds.size.height) + view.insertSubview(newVC.view, belowSubview: oldVC.view) UIView.animate(withDuration: ContainerViewController.animationDuration, delay: 0, options: ContainerViewController.animationOptions, animations: { - oldVC.view.alpha = 0.0 - oldVC.view.frame = frame + oldVC.view.alpha = 0.0 + oldVC.view.frame = frame }, - completion: { (_) in - oldVC.view.removeFromSuperview() - oldVC.removeFromParent() - newVC.didMove(toParent: self) + completion: { _ in + oldVC.view.removeFromSuperview() + oldVC.removeFromParent() + newVC.didMove(toParent: self) }) } } else { @@ -131,20 +130,20 @@ public class ContainerViewController: UIViewController { override public func viewDidLoad() { super.viewDidLoad() - if !self.children.contains(viewController) { + if !children.contains(viewController) { let subview = viewController.view! subview.autoresizingMask = [.flexibleWidth, .flexibleHeight] - subview.frame = self.view.bounds + subview.frame = view.bounds addChild(viewController) - self.view.addSubview(subview) + view.addSubview(subview) viewController.didMove(toParent: self) } } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() - self.view.subviews.first?.frame = self.view.bounds + view.subviews.first?.frame = view.bounds } override public func willMove(toParent parent: UIViewController?) { @@ -166,21 +165,15 @@ public class ContainerViewController: UIViewController { } override public var preferredStatusBarStyle: UIStatusBarStyle { - get { - return viewController.preferredStatusBarStyle - } + return viewController.preferredStatusBarStyle } override public var shouldAutorotate: Bool { - get { - return viewController.shouldAutorotate - } + return viewController.shouldAutorotate } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { - get { - return viewController.supportedInterfaceOrientations - } + return viewController.supportedInterfaceOrientations } } diff --git a/Example/Harmony/Utils/LazyView.swift b/Example/Harmony/Utils/LazyView.swift index d07846b7..2f4b576d 100644 --- a/Example/Harmony/Utils/LazyView.swift +++ b/Example/Harmony/Utils/LazyView.swift @@ -21,6 +21,7 @@ public struct LazyView: View { public init(_ build: @autoclosure @escaping () -> Content) { self.build = build } + public var body: Content { build() } diff --git a/Example/Harmony/Utils/MultiRequestAdapter.swift b/Example/Harmony/Utils/MultiRequestAdapter.swift index df51eb9d..e894fcf8 100644 --- a/Example/Harmony/Utils/MultiRequestAdapter.swift +++ b/Example/Harmony/Utils/MultiRequestAdapter.swift @@ -14,18 +14,21 @@ // limitations under the License. // -import Foundation import Alamofire +import Foundation public class MultiRequestAdapter: RequestAdapter { - private var adapters: [RequestAdapter] = [] public init(_ adapters: [RequestAdapter]) { self.adapters = adapters } - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + public func adapt( + _ urlRequest: URLRequest, + for session: Session, + completion: @escaping (Result) -> Void + ) { for adapter in adapters { adapter.adapt(urlRequest, for: session, completion: completion) } diff --git a/Example/Harmony/Utils/URLLoggerRequestAdapter.swift b/Example/Harmony/Utils/URLLoggerRequestAdapter.swift index c9e4bc95..dac1cc7f 100644 --- a/Example/Harmony/Utils/URLLoggerRequestAdapter.swift +++ b/Example/Harmony/Utils/URLLoggerRequestAdapter.swift @@ -14,15 +14,14 @@ // limitations under the License. // -import Foundation import Alamofire +import Foundation import Harmony /// /// Logs CURLS of incoming requests /// public class URLLoggerRequestAdapter: RequestAdapter { - private let logger: Logger private let tag: String? @@ -31,7 +30,11 @@ public class URLLoggerRequestAdapter: RequestAdapter { self.tag = tag } - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + public func adapt( + _ urlRequest: URLRequest, + for _: Session, + completion: @escaping (Result) -> Void + ) { let curl = urlRequest.curl(pretty: true) logger.info(tag: tag, "\(curl)") return completion(.success(urlRequest)) @@ -47,13 +50,13 @@ private extension URLRequest { var header = "" - if let httpHeaders = self.allHTTPHeaderFields, !httpHeaders.keys.isEmpty { + if let httpHeaders = allHTTPHeaderFields, !httpHeaders.keys.isEmpty { for (key, value) in httpHeaders { header += "-H \"\(key): \(value)\" \(complement)" } } - if let bodyData = self.httpBody, let bodyString = String(data: bodyData, encoding: .utf8) { + if let bodyData = httpBody, let bodyString = String(data: bodyData, encoding: .utf8) { data = "-d \"\(bodyString)\" \(complement)" } diff --git a/Example/Tests/Future+DeallocTests.swift b/Example/Tests/Future+DeallocTests.swift index 8072bf13..2e2b62e3 100644 --- a/Example/Tests/Future+DeallocTests.swift +++ b/Example/Tests/Future+DeallocTests.swift @@ -18,7 +18,6 @@ import XCTest @testable import Harmony class FutureDeallocTests: XCTestCase { - func testFuturePendingDealloc() { weak var weakFuture: Future? autoreleasepool { @@ -29,5 +28,4 @@ class FutureDeallocTests: XCTestCase { } XCTAssertNil(weakFuture) } - } diff --git a/Example/Tests/Future+InitTests.swift b/Example/Tests/Future+InitTests.swift index 106cb118..c796ff38 100755 --- a/Example/Tests/Future+InitTests.swift +++ b/Example/Tests/Future+InitTests.swift @@ -18,7 +18,6 @@ import XCTest @testable import Harmony class FutureInitTests: XCTestCase { - func testFutureEmptyConstructor() { // Arrange & Act. let future = Future() @@ -35,7 +34,7 @@ class FutureInitTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -52,7 +51,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -66,7 +65,7 @@ class FutureInitTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -84,7 +83,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -98,7 +97,7 @@ class FutureInitTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -116,7 +115,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -132,7 +131,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -144,7 +143,7 @@ class FutureInitTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -160,7 +159,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -174,7 +173,7 @@ class FutureInitTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } diff --git a/Example/Tests/Future+SetTests.swift b/Example/Tests/Future+SetTests.swift index d53a07ed..45797efd 100644 --- a/Example/Tests/Future+SetTests.swift +++ b/Example/Tests/Future+SetTests.swift @@ -18,7 +18,6 @@ import XCTest @testable import Harmony class FutureSetTests: XCTestCase { - func testFutureSetValue() { // Arrange let future = Future() @@ -30,7 +29,7 @@ class FutureSetTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -49,7 +48,7 @@ class FutureSetTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -69,7 +68,7 @@ class FutureSetTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -88,7 +87,7 @@ class FutureSetTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -105,7 +104,7 @@ class FutureSetTests: XCTestCase { XCTAssertTrue(future.state == Future.State.waitingThen) XCTAssertNotNil(future._result) switch future._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -126,7 +125,7 @@ class FutureSetTests: XCTestCase { switch future._result! { case .value: XCTAssert(false) - case .error(let error): + case let .error(error): XCTAssertTrue(error == Test.Error.code42) } } @@ -144,7 +143,7 @@ class FutureSetTests: XCTestCase { XCTAssertTrue(future2.state == .waitingThen) XCTAssertNotNil(future2._result) switch future2._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) @@ -164,7 +163,7 @@ class FutureSetTests: XCTestCase { XCTAssertTrue(future2.state == .waitingThen) XCTAssertNotNil(future2._result) switch future2._result! { - case .value(let value): + case let .value(value): XCTAssertEqual(value, 42) case .error: XCTAssert(false) diff --git a/Example/Tests/Future+ThenTests.swift b/Example/Tests/Future+ThenTests.swift index c37bd3f8..b6a92d45 100644 --- a/Example/Tests/Future+ThenTests.swift +++ b/Example/Tests/Future+ThenTests.swift @@ -18,7 +18,6 @@ import XCTest @testable import Harmony class FutureThenTests: XCTestCase { - func testFutureFirstSetAfterThen() { // Arrange + Act let future = Future(42) @@ -35,7 +34,7 @@ class FutureThenTests: XCTestCase { func testFutureFirstThenAfterSet() { // Arrange let future = Future() - let expectation1 = self.expectation(description: "1 then") + let expectation1 = expectation(description: "1 then") // Assert XCTAssertTrue(future.state == .blank) @@ -53,15 +52,15 @@ class FutureThenTests: XCTestCase { // Assert XCTAssertTrue(future.state == .sent) - self.wait(for: [expectation1], timeout: 1) + wait(for: [expectation1], timeout: 1) } func testFutureDoubleThen() { // Arrange + Act let future = Future(42) - let expectation1 = self.expectation(description: "1 then") - let expectation2 = self.expectation(description: "2 then") + let expectation1 = expectation(description: "1 then") + let expectation2 = expectation(description: "2 then") // Assert future.then { value in @@ -75,19 +74,19 @@ class FutureThenTests: XCTestCase { } XCTAssertTrue(future.state == .sent) - self.wait(for: [expectation1, expectation2], timeout: 1) + wait(for: [expectation1, expectation2], timeout: 1) } func testFutureLotsOfThen() { // Arrange + Act let future = Future(42) - let expectation1 = self.expectation(description: "1 then") - let expectation2 = self.expectation(description: "2 then") - let expectation3 = self.expectation(description: "3 then") - let expectation4 = self.expectation(description: "4 then") - let expectation5 = self.expectation(description: "5 then") - let expectation6 = self.expectation(description: "6 then") + let expectation1 = expectation(description: "1 then") + let expectation2 = expectation(description: "2 then") + let expectation3 = expectation(description: "3 then") + let expectation4 = expectation(description: "4 then") + let expectation5 = expectation(description: "5 then") + let expectation6 = expectation(description: "6 then") // Assert future.then { value in @@ -113,7 +112,6 @@ class FutureThenTests: XCTestCase { } XCTAssertTrue(future.state == .sent) - self.wait(for: [expectation1, expectation2, expectation3, expectation4, expectation5, expectation6], timeout: 1) + wait(for: [expectation1, expectation2, expectation3, expectation4, expectation5, expectation6], timeout: 1) } - } diff --git a/Example/Tests/Performance/FuturePerformanceTests.swift b/Example/Tests/Performance/FuturePerformanceTests.swift index e43c381f..48e1c817 100644 --- a/Example/Tests/Performance/FuturePerformanceTests.swift +++ b/Example/Tests/Performance/FuturePerformanceTests.swift @@ -19,7 +19,6 @@ import XCTest @testable import Harmony class FuturePerformanceTests: XCTestCase { - /// Measures the average time needed to create a resolved `Future` and get into a `then` block /// chained to it. func testThenOnSerialQueue() { @@ -109,7 +108,7 @@ class FuturePerformanceTests: XCTestCase { let queue = DispatchQueue(label: #function, qos: .userInitiated, attributes: .concurrent) let group = DispatchGroup() var futures = [Future]() - for _ in 0..() future.then(DispatchQueueExecutor(queue)) { _ in diff --git a/Example/Tests/Performance/GCDPerformanceTests.swift b/Example/Tests/Performance/GCDPerformanceTests.swift index f4d222a6..fb7911f6 100644 --- a/Example/Tests/Performance/GCDPerformanceTests.swift +++ b/Example/Tests/Performance/GCDPerformanceTests.swift @@ -18,7 +18,6 @@ import UIKit import XCTest class GCDPerformanceTests: XCTestCase { - /// Measures the average time needed to get into a dispatch_async block. func testDispatchAsyncOnSerialQueue() { // Arrange. @@ -104,11 +103,11 @@ class GCDPerformanceTests: XCTestCase { let queue = DispatchQueue(label: #function, qos: .userInitiated, attributes: .concurrent) let group = DispatchGroup() var blocks = [() -> Void]() - for _ in 0..]() - for _ in 0...pending() promise.then(on: queue) { _ in diff --git a/Example/Tests/TestHelper.swift b/Example/Tests/TestHelper.swift index 6c3aa4e0..cc46ca38 100644 --- a/Example/Tests/TestHelper.swift +++ b/Example/Tests/TestHelper.swift @@ -19,7 +19,7 @@ import Foundation // MARK: - Constants struct Constants { - static let iterationCount = 10_000 + static let iterationCount = 10000 } // MARK: - Helpers @@ -33,13 +33,14 @@ func print(total time: TimeInterval) { } /// Namespace for test helpers. -public struct Test { +public enum Test { public enum Error: Int, CustomNSError { case code13 = 13 case code42 = 42 public static var errorDomain: String { return "com.mobilejazz.Harmony" } + public var errorCode: Int { return rawValue } public var errorUserInfo: [String: Any] { return [:] } } diff --git a/Package.swift b/Package.swift index ca345056..4ec7fc5d 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let package = Package( name: "Harmony", platforms: [ .iOS(.v12), - .macOS(.v10_15) + .macOS(.v10_15), ], products: [ .library( @@ -17,7 +17,7 @@ let package = Package( .library( name: "HarmonyTesting", targets: ["HarmonyTesting"] - ) + ), ], targets: [ .target( @@ -31,6 +31,6 @@ let package = Package( .testTarget( name: "HarmonyTests", dependencies: ["Harmony"] - ) + ), ] ) diff --git a/Sources/Harmony/Common/Error/ClassError.swift b/Sources/Harmony/Common/Error/ClassError.swift index 6295dc69..537aa7b9 100644 --- a/Sources/Harmony/Common/Error/ClassError.swift +++ b/Sources/Harmony/Common/Error/ClassError.swift @@ -41,7 +41,6 @@ import Foundation /// } /// open class ClassError: Error, CustomStringConvertible { - /// The error's domain public let domain: String diff --git a/Sources/Harmony/Common/Error/CoreError.swift b/Sources/Harmony/Common/Error/CoreError.swift index 7dc9222a..a04c1758 100644 --- a/Sources/Harmony/Common/Error/CoreError.swift +++ b/Sources/Harmony/Common/Error/CoreError.swift @@ -20,8 +20,7 @@ import Foundation /// CoreError is used as a namespace /// public struct CoreError { - - private init() { } + private init() {} // The domain for all CoreError errors. public static let domain = "com.mobilejazz.core.error" @@ -32,7 +31,7 @@ public struct CoreError { super.init(domain: CoreError.domain, code: 0, description: description) } - public override init(domain: String, code: Int, description: String) { + override public init(domain: String, code: Int, description: String) { super.init(domain: domain, code: code, description: description) } } @@ -79,10 +78,9 @@ public struct CoreError { } } -extension CoreError { - +public extension CoreError { /// A base implementation for NSError to ClassError conversion - public class NSError: Unknown { + class NSError: Unknown { /// The NSError public let error: Foundation.NSError @@ -94,13 +92,13 @@ extension CoreError { super.init(domain: error.domain, code: error.code, description: error.localizedDescription) } - public override func userInfo() -> [String: Any] { + override public func userInfo() -> [String: Any] { return error.userInfo } } /// OSStatus fail error. Subtype of Failed error. - public class OSStatusFailure: Failed { + class OSStatusFailure: Failed { /// The OSStatus public let status: OSStatus @@ -114,7 +112,7 @@ extension CoreError { super.init(description ?? "OSStatus failure with code \(status)") } - public override func userInfo() -> [String: Any] { + override public func userInfo() -> [String: Any] { var userInfo = super.userInfo() userInfo["OSStatus"] = status return userInfo diff --git a/Sources/Harmony/Common/Error/ErrorHelper.swift b/Sources/Harmony/Common/Error/ErrorHelper.swift index 6c61f556..c91116c5 100644 --- a/Sources/Harmony/Common/Error/ErrorHelper.swift +++ b/Sources/Harmony/Common/Error/ErrorHelper.swift @@ -42,6 +42,6 @@ public extension NSError { subdomain: String, code: Int = 0, userInfo: (inout [String: Any]) -> Void = { _ in }) { - self.init(message, reason: reason, domain: NSError.domain(subdomain), code: code, userInfo: userInfo ) + self.init(message, reason: reason, domain: NSError.domain(subdomain), code: code, userInfo: userInfo) } } diff --git a/Sources/Harmony/Common/Extensions/Data+Extensions.swift b/Sources/Harmony/Common/Extensions/Data+Extensions.swift index 5f291115..4510b7ed 100644 --- a/Sources/Harmony/Common/Extensions/Data+Extensions.swift +++ b/Sources/Harmony/Common/Extensions/Data+Extensions.swift @@ -14,15 +14,14 @@ // limitations under the License. // -import Foundation import CommonCrypto +import Foundation -extension Data { - +public extension Data { /// Creates random data of the given length. /// /// - Parameter length: The length of the data. - public init?(randomOfLength length: UInt) { + init?(randomOfLength length: UInt) { var bytes = [UInt8](repeating: 0, count: Int(length)) let status = SecRandomCopyBytes(kSecRandomDefault, Int(length), &bytes) if status == errSecSuccess { @@ -33,7 +32,7 @@ extension Data { } /// HexEncoding options - public struct HexEncodingOptions: OptionSet { + struct HexEncodingOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue @@ -46,7 +45,7 @@ extension Data { /// /// - Parameter options: Use .upperCase if needed. /// - Returns: The hexadecimal string representation. - public func hexEncodedString(options: HexEncodingOptions = []) -> String { + func hexEncodedString(options: HexEncodingOptions = []) -> String { let hexDigits = Array((options.contains(.upperCase) ? "0123456789ABCDEF" : "0123456789abcdef").utf16) var chars: [unichar] = [] chars.reserveCapacity(2 * count) @@ -57,7 +56,7 @@ extension Data { return String(utf16CodeUnits: chars, count: chars.count) } - public init?(hexEncoded string: String) { + init?(hexEncoded string: String) { // Get the UTF8 characters of this string let chars = Array(string.utf8) @@ -74,25 +73,25 @@ extension Data { let map: [UInt8] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>? - 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // HIJKLMNO + 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, // @ABCDEFG + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // HIJKLMNO ] // Grab two characters at a time, map them and turn it into a byte for i in stride(from: 0, to: string.count, by: 2) { let char1 = chars[i] - let char2 = chars[i+1] + let char2 = chars[i + 1] // ASCII validation - guard (48 /* 0 */<= char1 && char1 <= 57 /* 9 */) || - (65 /* a */<= char1 && char1 <= 70 /* f */) || - (97 /* A */ <= char1 && char1 <= 102 /* F */) else { + guard (48 /* 0 */ <= char1 && char1 <= 57 /* 9 */ ) || + (65 /* a */ <= char1 && char1 <= 70 /* f */ ) || + (97 /* A */ <= char1 && char1 <= 102 /* F */ ) else { return nil } - guard (48 /* 0 */<= char2 && char2 <= 57 /* 9 */) || - (65 /* a */<= char2 && char2 <= 70 /* f */) || - (97 /* A */ <= char2 && char2 <= 102 /* F */) else { + guard (48 /* 0 */ <= char2 && char2 <= 57 /* 9 */ ) || + (65 /* a */ <= char2 && char2 <= 70 /* f */ ) || + (97 /* A */ <= char2 && char2 <= 102 /* F */ ) else { return nil } @@ -104,18 +103,18 @@ extension Data { self.init(bytes) } - public func sha256() -> String { + func sha256() -> String { return digest().hexEncodedString() } private func digest() -> Data { let digestLength = Int(CC_SHA256_DIGEST_LENGTH) var hash = [UInt8](repeating: 0, count: digestLength) - CC_SHA256((self as NSData).bytes, UInt32(self.count), &hash) + CC_SHA256((self as NSData).bytes, UInt32(count), &hash) return NSData(bytes: hash, length: digestLength) as Data } - private func hexStringFromData(input: NSData) -> String { + private func hexStringFromData(input: NSData) -> String { var bytes = [UInt8](repeating: 0, count: input.length) input.getBytes(&bytes, length: input.length) @@ -130,7 +129,7 @@ extension Data { public extension String { func sha256() -> String { - if let stringData = self.data(using: String.Encoding.utf8) { + if let stringData = data(using: String.Encoding.utf8) { return stringData.sha256() } return "" diff --git a/Sources/Harmony/Common/Extensions/JSONDecoding.swift b/Sources/Harmony/Common/Extensions/JSONDecoding.swift index ac28b55c..831bfc30 100644 --- a/Sources/Harmony/Common/Extensions/JSONDecoding.swift +++ b/Sources/Harmony/Common/Extensions/JSONDecoding.swift @@ -17,8 +17,10 @@ import Foundation public extension Dictionary where Key == String, Value == AnyObject { - func decodeAs(_ type: T.Type, - keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) throws -> T where T: Decodable { + func decodeAs( + _ type: T.Type, + keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys + ) throws -> T where T: Decodable { let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) let decoder = JSONDecoder() decoder.keyDecodingStrategy = keyDecodingStrategy @@ -33,18 +35,19 @@ public extension Dictionary where Key == String, Value == AnyObject { var object: T = try decodeAs(type, keyDecodingStrategy: keyDecodingStrategy) completion(&object) return Future(object) - } catch let error { + } catch { return Future(error) } } } public extension Array where Element == [String: AnyObject] { - func decodeAs(keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) throws -> [T] where T: Decodable { + func decodeAs(keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) throws -> [T] + where T: Decodable { let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) let decoder = JSONDecoder() decoder.keyDecodingStrategy = keyDecodingStrategy - let array = try decoder.decode(Array.self, from: data) + let array = try decoder.decode([T].self, from: data) return array } @@ -54,11 +57,11 @@ public extension Array where Element == [String: AnyObject] { do { var array: [T] = try decodeAs(keyDecodingStrategy: keyDecodingStrategy) for index in array.indices { - forEach(&(array[index])) + forEach(&array[index]) } completion(&array) return Future(array) - } catch let error { + } catch { return Future(error) } } diff --git a/Sources/Harmony/Common/Extensions/Number+Extensions.swift b/Sources/Harmony/Common/Extensions/Number+Extensions.swift index db53526d..6012804a 100644 --- a/Sources/Harmony/Common/Extensions/Number+Extensions.swift +++ b/Sources/Harmony/Common/Extensions/Number+Extensions.swift @@ -20,7 +20,7 @@ public extension Int { /// Returns a random value. /// - Returns: A random value. static func random() -> Int { - return Int.random(in: Int.min...Int.max) + return Int.random(in: Int.min ... Int.max) } } @@ -28,7 +28,7 @@ public extension Int8 { /// Returns a random value. /// - Returns: A random value. static func random() -> Int8 { - return Int8.random(in: Int8.min...Int8.max) + return Int8.random(in: Int8.min ... Int8.max) } } @@ -36,7 +36,7 @@ public extension Int16 { /// Returns a random value. /// - Returns: A random value. static func random() -> Int16 { - return Int16.random(in: Int16.min...Int16.max) + return Int16.random(in: Int16.min ... Int16.max) } } @@ -44,7 +44,7 @@ public extension Int32 { /// Returns a random value. /// - Returns: A random value. static func random() -> Int32 { - return Int32.random(in: Int32.min...Int32.max) + return Int32.random(in: Int32.min ... Int32.max) } } @@ -52,7 +52,7 @@ public extension Int64 { /// Returns a random value. /// - Returns: A random value. static func random() -> Int64 { - return Int64.random(in: Int64.min...Int64.max) + return Int64.random(in: Int64.min ... Int64.max) } } @@ -60,7 +60,7 @@ public extension UInt { /// Returns a random value. /// - Returns: A random value. static func random() -> UInt { - return UInt.random(in: UInt.min...UInt.max) + return UInt.random(in: UInt.min ... UInt.max) } } @@ -68,7 +68,7 @@ public extension UInt8 { /// Returns a random value. /// - Returns: A random value. static func random() -> UInt8 { - return UInt8.random(in: UInt8.min...UInt8.max) + return UInt8.random(in: UInt8.min ... UInt8.max) } } @@ -76,7 +76,7 @@ public extension UInt16 { /// Returns a random value. /// - Returns: A random value. static func random() -> UInt16 { - return UInt16.random(in: UInt16.min...UInt16.max) + return UInt16.random(in: UInt16.min ... UInt16.max) } } @@ -84,7 +84,7 @@ public extension UInt32 { /// Returns a random value. /// - Returns: A random value. static func random() -> UInt32 { - return UInt32.random(in: UInt32.min...UInt32.max) + return UInt32.random(in: UInt32.min ... UInt32.max) } } @@ -92,7 +92,7 @@ public extension UInt64 { /// Returns a random value. /// - Returns: A random value. static func random() -> UInt64 { - return UInt64.random(in: UInt64.min...UInt64.max) + return UInt64.random(in: UInt64.min ... UInt64.max) } } @@ -100,7 +100,7 @@ public extension Float { /// Returns a random value. /// - Returns: A random value. static func random() -> Float { - return Float.random(in: Float.leastNormalMagnitude...Float.greatestFiniteMagnitude) + return Float.random(in: Float.leastNormalMagnitude ... Float.greatestFiniteMagnitude) } } @@ -108,6 +108,6 @@ public extension Double { /// Returns a random value. /// - Returns: A random value. static func random() -> Double { - return Double.random(in: Double.leastNormalMagnitude...Double.greatestFiniteMagnitude) + return Double.random(in: Double.leastNormalMagnitude ... Double.greatestFiniteMagnitude) } } diff --git a/Sources/Harmony/Common/Extensions/String+Extensions.swift b/Sources/Harmony/Common/Extensions/String+Extensions.swift index ace6ac4e..3f77e1d1 100644 --- a/Sources/Harmony/Common/Extensions/String+Extensions.swift +++ b/Sources/Harmony/Common/Extensions/String+Extensions.swift @@ -14,21 +14,81 @@ // limitations under the License. // -import Foundation import CommonCrypto +import Foundation -private let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] +private let alphabet = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", +] public extension String { - /// Creates a random string of the given length. /// /// - Parameter length: The length of the string. init(randomOfLength length: UInt) { var string = "" - for _ in 0.. String { - if let first = self.words().first { + if let first = words().first { return first } return self @@ -56,7 +116,7 @@ public extension String { /// /// - Returns: The last word. func lastWord() -> String { - if let last = self.words().last { + if let last = words().last { return last } return self @@ -73,7 +133,7 @@ public extension String { } let first = words.first! - guard first.count + 1 < self.count else { + guard first.count + 1 < count else { return "" } @@ -87,18 +147,18 @@ public extension String { /// /// - Returns: A MD5 Hashed string func md5() -> String { - guard let data = self.data(using: .utf8) else { + guard let data = data(using: .utf8) else { return self } var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) #if swift(>=5.0) - _ = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in - return CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest) - } + _ = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in + CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest) + } #else - _ = data.withUnsafeBytes { bytes in - return CC_MD5(bytes, CC_LONG(data.count), &digest) - } + _ = data.withUnsafeBytes { bytes in + CC_MD5(bytes, CC_LONG(data.count), &digest) + } #endif return digest.map { String(format: "%02x", $0) }.joined() } diff --git a/Sources/Harmony/Common/JSON/CodingKeyStrategies.swift b/Sources/Harmony/Common/JSON/CodingKeyStrategies.swift index 1b0f55a4..060ccaf8 100644 --- a/Sources/Harmony/Common/JSON/CodingKeyStrategies.swift +++ b/Sources/Harmony/Common/JSON/CodingKeyStrategies.swift @@ -16,9 +16,8 @@ import Foundation -extension JSONEncoder.KeyEncodingStrategy { - - public static func map(_ keys: [String: String]) -> JSONEncoder.KeyEncodingStrategy { +public extension JSONEncoder.KeyEncodingStrategy { + static func map(_ keys: [String: String]) -> JSONEncoder.KeyEncodingStrategy { return .custom { codingKeys in let originalKey = codingKeys.last! @@ -32,9 +31,8 @@ extension JSONEncoder.KeyEncodingStrategy { } } -extension JSONDecoder.KeyDecodingStrategy { - - public static func map(_ keys: [String: String]) -> JSONDecoder.KeyDecodingStrategy { +public extension JSONDecoder.KeyDecodingStrategy { + static func map(_ keys: [String: String]) -> JSONDecoder.KeyDecodingStrategy { return .custom { codingKeys in let originalKey = codingKeys.last! diff --git a/Sources/Harmony/Common/JSON/MutableCodingKey.swift b/Sources/Harmony/Common/JSON/MutableCodingKey.swift index 32f3c48d..19a11f6a 100644 --- a/Sources/Harmony/Common/JSON/MutableCodingKey.swift +++ b/Sources/Harmony/Common/JSON/MutableCodingKey.swift @@ -20,7 +20,6 @@ import Foundation /// Wrapper to allow us to edit a coding key. /// public struct MutableCodingKey: CodingKey { - public var stringValue: String public var intValue: Int? @@ -33,7 +32,7 @@ public struct MutableCodingKey: CodingKey { } public init(intValue: Int) { - self.stringValue = "\(intValue)" + stringValue = "\(intValue)" self.intValue = intValue } diff --git a/Sources/Harmony/Common/KeyValueObserver.swift b/Sources/Harmony/Common/KeyValueObserver.swift index 6a15205a..8be23200 100644 --- a/Sources/Harmony/Common/KeyValueObserver.swift +++ b/Sources/Harmony/Common/KeyValueObserver.swift @@ -20,7 +20,6 @@ import Foundation /// Swift object acting as a key value observer /// public class KeyValueObserver: NSObject where V: Any { - private var context: String private let resolver: ObservableResolver private var keyPath: String @@ -32,7 +31,7 @@ public class KeyValueObserver: NSObject where V: Any { /// - target: The object to observe /// - keyPath: The keyPath to observe /// - closure: The callback closure - public convenience init(target: NSObject, keyPath: String, _ closure: @escaping (V) -> Void ) { + public convenience init(target: NSObject, keyPath: String, _ closure: @escaping (V) -> Void) { let observable = Observable() observable.then { closure($0) } self.init(target: target, keyPath: keyPath, resolver: ObservableResolver(observable)) @@ -48,7 +47,7 @@ public class KeyValueObserver: NSObject where V: Any { self.keyPath = keyPath self.target = target self.resolver = resolver - self.context = "com.mobilejazz.KeyValueObserver<\(String(describing: V.self))>.\(keyPath)" + context = "com.mobilejazz.KeyValueObserver<\(String(describing: V.self))>.\(keyPath)" super.init() self.target.addObserver(self, forKeyPath: keyPath, options: .new, context: &context) } @@ -57,7 +56,12 @@ public class KeyValueObserver: NSObject where V: Any { self.target.removeObserver(self, forKeyPath: keyPath) } - public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { + override public func observeValue( + forKeyPath keyPath: String?, + of _: Any?, + change: [NSKeyValueChangeKey: Any]?, + context: UnsafeMutableRawPointer? + ) { if context == &self.context, let path = keyPath, path == self.keyPath { if let value = change?[NSKeyValueChangeKey.newKey] { resolver.set(value as! V) diff --git a/Sources/Harmony/Common/LinkRecognizer.swift b/Sources/Harmony/Common/LinkRecognizer.swift index 7894c896..c998182b 100644 --- a/Sources/Harmony/Common/LinkRecognizer.swift +++ b/Sources/Harmony/Common/LinkRecognizer.swift @@ -18,35 +18,37 @@ import Foundation public protocol LinkRecognizerObserver: AnyObject { func linkRecognizer(_ linkRecognizer: LinkRecognizer, didRecognizeURLForKey key: String, components: [String]) - func linkRecognizer(_ linkRecognizer: LinkRecognizer, didFailToRecognizeURL url: URL, result: LinkRecognizer.Result) + func linkRecognizer( + _ linkRecognizer: LinkRecognizer, + didFailToRecognizeURL url: URL, + result: LinkRecognizer.Result + ) } public protocol LinkRecognizerDelegate: AnyObject { - func linkRecognizer(_ linkRecognizer: LinkRecognizer, willRecognizeURLForKey key: String, components: [String]) -> Bool + func linkRecognizer(_ linkRecognizer: LinkRecognizer, willRecognizeURLForKey key: String, + components: [String]) -> Bool } public class LinkRecognizer { - public enum Result: CustomStringConvertible { case valid([String]) case unknownScheme case unsupportedLink public var description: String { - get { - switch self { - case .valid(let components): - return "Valid with components: \(components)" - case .unknownScheme: - return "UnkonwnScheme" - case .unsupportedLink: - return "UnsupportedLink" - } + switch self { + case let .valid(components): + return "Valid with components: \(components)" + case .unknownScheme: + return "UnkonwnScheme" + case .unsupportedLink: + return "UnsupportedLink" } } } - public struct Pattern { + public enum Pattern { public static let numeric = "(\\d+)" public static let nonNumeric = "(\\D+)" public static let alphanumeric = "(\\w+)" @@ -59,10 +61,11 @@ public class LinkRecognizer { public init(rawValue: Int) { self.rawValue = rawValue } - public static let none = Options([]) - public static let anchoredStart = Options(rawValue: 1 << 0) - public static let anchoredEnd = Options(rawValue: 1 << 1) - public static let caseInsensitive = Options(rawValue: 1 << 2) + + public static let none = Options([]) + public static let anchoredStart = Options(rawValue: 1 << 0) + public static let anchoredEnd = Options(rawValue: 1 << 1) + public static let caseInsensitive = Options(rawValue: 1 << 2) } public weak var delegate: LinkRecognizerDelegate? @@ -94,7 +97,8 @@ public class LinkRecognizer { return Result.unsupportedLink } - let regexOptions = options.contains(.caseInsensitive) ? NSRegularExpression.Options.caseInsensitive : NSRegularExpression.Options(rawValue: 0) + let regexOptions = options.contains(.caseInsensitive) ? NSRegularExpression.Options + .caseInsensitive : NSRegularExpression.Options(rawValue: 0) for (key, pattern) in patterns { var patternStr = pattern @@ -111,7 +115,7 @@ public class LinkRecognizer { options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: linkStr.count)) { var captures: [String] = [] - for index in 0.. String { switch level { case .trace: diff --git a/Sources/Harmony/Common/Logger/Logger.swift b/Sources/Harmony/Common/Logger/Logger.swift index d9b5b7c6..2fccb6ae 100644 --- a/Sources/Harmony/Common/Logger/Logger.swift +++ b/Sources/Harmony/Common/Logger/Logger.swift @@ -28,7 +28,6 @@ import Foundation /// Abstracts concrete implementations of a logger system. @objc(MJLogger) public protocol Logger { - /// Logs a String object using a given level /// /// - Parameters: @@ -46,15 +45,15 @@ import Foundation } // MARK: - Default implementations -public extension Logger { +public extension Logger { /// Logs a String message using an trace level. /// /// - Parameters: /// - tag: An additional label to help categorise logs. /// - message: String to be logged func trace(tag: String? = nil, _ message: String) { - self.log(level: .trace, tag: tag, message: message) + log(level: .trace, tag: tag, message: message) } /// Logs a String message using an debug level. @@ -63,7 +62,7 @@ public extension Logger { /// - tag: An additional label to help categorise logs. /// - message: String to be logged func debug(tag: String? = nil, _ message: String) { - self.log(level: .debug, tag: tag, message: message) + log(level: .debug, tag: tag, message: message) } /// Logs a String message using an info level. @@ -72,7 +71,7 @@ public extension Logger { /// - tag: An additional label to help categorise logs. /// - message: String to be logged func info(tag: String? = nil, _ message: String) { - self.log(level: .info, tag: tag, message: message) + log(level: .info, tag: tag, message: message) } /// Logs a String message using a warning level. @@ -81,7 +80,7 @@ public extension Logger { /// - tag: An additional label to help categorise logs. /// - message: String to be logged func warning(tag: String? = nil, _ message: String) { - self.log(level: .warning, tag: tag, message: message) + log(level: .warning, tag: tag, message: message) } /// Logs a String message using an error level. @@ -90,7 +89,7 @@ public extension Logger { /// - tag: An additional label to help categorise logs. /// - message: String to be logged func error(tag: String? = nil, _ message: String) { - self.log(level: .error, tag: tag, message: message) + log(level: .error, tag: tag, message: message) } /// Logs a String message using a fatal level. @@ -99,7 +98,7 @@ public extension Logger { /// - tag: An additional label to help categorise logs. /// - message: String to be logged func fatal(tag: String? = nil, _ message: String) { - self.log(level: .fatal, tag: tag, message: message) + log(level: .fatal, tag: tag, message: message) } /// Logs a key-value pair @@ -108,13 +107,13 @@ public extension Logger { /// - key: They key /// - value: The value func log(key: String, value: Any?) { - self.info("\(key)=\(value ?? "-")") + info("\(key)=\(value ?? "-")") } } /// Logger that does nothing. public class VoidLogger: Logger { public init() {} - public func log(level: LogLevel, tag: String?, message: String) {} - public func log(key: String, value: Any?) {} + public func log(level _: LogLevel, tag _: String?, message _: String) {} + public func log(key _: String, value _: Any?) {} } diff --git a/Sources/Harmony/Common/ScopeLock/ScopeLock.swift b/Sources/Harmony/Common/ScopeLock/ScopeLock.swift index e5520fbe..83c3b74e 100644 --- a/Sources/Harmony/Common/ScopeLock/ScopeLock.swift +++ b/Sources/Harmony/Common/ScopeLock/ScopeLock.swift @@ -55,8 +55,8 @@ private class DictionaryLockProvider: LockProvider where T: Hashable { } } -private let objectLockProvider = MapTableLockProvider() -private let stringLockProvider = DictionaryLockProvider() +private let objectLockProvider = MapTableLockProvider() +private let stringLockProvider = DictionaryLockProvider() private let integerLockProvider = DictionaryLockProvider() private let typeLockProvider = DictionaryLockProvider() @@ -73,7 +73,6 @@ private let typeLockProvider = DictionaryLockProvider() /// } /// } public struct ScopeLock { - /// The scope /// /// - none: No scope defined. The ScopeLock will be instance specific. @@ -99,15 +98,15 @@ public struct ScopeLock { switch scope { case .none: lock = NSLock() - case .lock(let inLock): + case let .lock(inLock): lock = inLock case .global: lock = typeLockProvider.lockWithScope(String(describing: T.self)) - case .object(let object): + case let .object(object): lock = objectLockProvider.lockWithScope(object) - case .string(let string): + case let .string(string): lock = stringLockProvider.lockWithScope(string) - case .int(let integer): + case let .int(integer): lock = integerLockProvider.lockWithScope(integer) } } @@ -127,7 +126,7 @@ public struct ScopeLock { self.init(Scope.object(object)) } - public init(_ type: T.Type) { + public init(_: T.Type) { self.init(Scope.global) } diff --git a/Sources/Harmony/Data/DataSource/AnyDataSource.swift b/Sources/Harmony/Data/DataSource/AnyDataSource.swift index 7f823dca..af1cbeb8 100644 --- a/Sources/Harmony/Data/DataSource/AnyDataSource.swift +++ b/Sources/Harmony/Data/DataSource/AnyDataSource.swift @@ -19,7 +19,7 @@ import Foundation /// /// Type eraser class for DataSource, following Apple's Swift Standard Library approach. /// -public final class AnyDataSource : GetDataSource, PutDataSource, DeleteDataSource { +public final class AnyDataSource: GetDataSource, PutDataSource, DeleteDataSource { private let box: DataSourceBoxBase /// Default initializer. @@ -57,40 +57,41 @@ public final class AnyDataSource : GetDataSource, PutDataSource, DeleteDataS /// /// This is an abstract class. Do not use it. -/// DataSource base class defining a generic type T (which is unrelated to the associated type of the DataSource protocol) +/// DataSource base class defining a generic type T (which is unrelated to the associated type of the DataSource +// protocol) /// -internal class DataSourceBoxBase : GetDataSource, PutDataSource, DeleteDataSource { - - func get(_ query: Query) -> Future { +internal class DataSourceBoxBase: GetDataSource, PutDataSource, DeleteDataSource { + func get(_: Query) -> Future { fatalError("This method is abstract.") } - func getAll(_ query: Query) -> Future<[T]> { + func getAll(_: Query) -> Future<[T]> { fatalError("This method is abstract.") } - func put(_ value: T?, in query: Query) -> Future { + func put(_: T?, in _: Query) -> Future { fatalError("This method is abstract.") } - func putAll(_ array: [T], in query: Query) -> Future<[T]> { + func putAll(_: [T], in _: Query) -> Future<[T]> { fatalError("This method is abstract.") } - func delete(_ query: Query) -> Future { + func delete(_: Query) -> Future { fatalError("This method is abstract.") } - func deleteAll(_ query: Query) -> Future { + func deleteAll(_: Query) -> Future { fatalError("This method is abstract.") } } /// -/// A data source box, which has as generic type a DataSource and links the DataSourceBoxBase type T as the Base.T type. +/// A data source box, which has as generic type a DataSource and links the DataSourceBoxBase type T as the Base.T +// type. /// -internal class DataSourceBox : DataSourceBoxBase where Base: GetDataSource, Base: PutDataSource, Base: DeleteDataSource { - +internal class DataSourceBox: DataSourceBoxBase where Base: GetDataSource, Base: PutDataSource, + Base: DeleteDataSource { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/DataSource/AnyGetDataSource.swift b/Sources/Harmony/Data/DataSource/AnyGetDataSource.swift index 6c4f3181..286986b4 100644 --- a/Sources/Harmony/Data/DataSource/AnyGetDataSource.swift +++ b/Sources/Harmony/Data/DataSource/AnyGetDataSource.swift @@ -19,7 +19,7 @@ import Foundation /// /// Type eraser class for DataSource, following Apple's Swift Standard Library approach. /// -public final class AnyGetDataSource : GetDataSource { +public final class AnyGetDataSource: GetDataSource { private let box: GetDataSourceBoxBase /// Default initializer. @@ -39,11 +39,11 @@ public final class AnyGetDataSource : GetDataSource { } } -extension GetDataSource { +public extension GetDataSource { /// Returns an AnyGetDataSource abstraction of the current data source /// /// - Returns: An AnyGetDataSource abstraction - public func asAnyGetDataSource() -> AnyGetDataSource { + func asAnyGetDataSource() -> AnyGetDataSource { if let dataSource = self as? AnyGetDataSource { return dataSource } @@ -53,24 +53,24 @@ extension GetDataSource { /// /// This is an abstract class. Do not use it. -/// GetDataSource base class defining a generic type T (which is unrelated to the associated type of the GetDataSource protocol) +/// GetDataSource base class defining a generic type T (which is unrelated to the associated type of the +// GetDataSource protocol) /// -internal class GetDataSourceBoxBase : GetDataSource { - - func get(_ query: Query) -> Future { +internal class GetDataSourceBoxBase: GetDataSource { + func get(_: Query) -> Future { fatalError("This method is abstract.") } - func getAll(_ query: Query) -> Future<[T]> { + func getAll(_: Query) -> Future<[T]> { fatalError("This method is abstract.") } } /// -/// A data source box, which has as generic type a GetDataSource and links the GetDataSourceBoxBase type T as the Base.T type. +/// A data source box, which has as generic type a GetDataSource and links the GetDataSourceBoxBase type T as the +// Base.T type. /// -internal class GetDataSourceBox : GetDataSourceBoxBase { - +internal class GetDataSourceBox: GetDataSourceBoxBase { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/DataSource/AnyPutDataSource.swift b/Sources/Harmony/Data/DataSource/AnyPutDataSource.swift index 684b210a..b6ab3b48 100644 --- a/Sources/Harmony/Data/DataSource/AnyPutDataSource.swift +++ b/Sources/Harmony/Data/DataSource/AnyPutDataSource.swift @@ -19,7 +19,7 @@ import Foundation /// /// Type eraser class for DataSource, following Apple's Swift Standard Library approach. /// -public final class AnyPutDataSource : PutDataSource { +public final class AnyPutDataSource: PutDataSource { private let box: PutDataSourceBoxBase /// Default initializer. @@ -39,11 +39,11 @@ public final class AnyPutDataSource : PutDataSource { } } -extension PutDataSource { +public extension PutDataSource { /// Returns an AnyPutDataSource abstraction of the current data source /// /// - Returns: An AnyPutDataSource abstraction - public func asAnyPutDataSource() -> AnyPutDataSource { + func asAnyPutDataSource() -> AnyPutDataSource { if let dataSource = self as? AnyPutDataSource { return dataSource } @@ -53,24 +53,24 @@ extension PutDataSource { /// /// This is an abstract class. Do not use it. -/// PutDataSource base class defining a generic type T (which is unrelated to the associated type of the PutDataSource protocol) +/// PutDataSource base class defining a generic type T (which is unrelated to the associated type of the +// PutDataSource protocol) /// -internal class PutDataSourceBoxBase : PutDataSource { - - func put(_ value: T?, in query: Query) -> Future { +internal class PutDataSourceBoxBase: PutDataSource { + func put(_: T?, in _: Query) -> Future { fatalError("This method is abstract.") } - func putAll(_ array: [T], in query: Query) -> Future<[T]> { + func putAll(_: [T], in _: Query) -> Future<[T]> { fatalError("This method is abstract.") } } /// -/// A data source box, which has as generic type a PutDataSource and links the PutDataSourceBoxBase type T as the Base.T type. +/// A data source box, which has as generic type a PutDataSource and links the PutDataSourceBoxBase type T as the +// Base.T type. /// -internal class PutDataSourceBox : PutDataSourceBoxBase { - +internal class PutDataSourceBox: PutDataSourceBoxBase { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/DataSource/DataSource.swift b/Sources/Harmony/Data/DataSource/DataSource.swift index 33d6be70..64fb238e 100644 --- a/Sources/Harmony/Data/DataSource/DataSource.swift +++ b/Sources/Harmony/Data/DataSource/DataSource.swift @@ -16,13 +16,12 @@ import Foundation -public protocol DataSource { } +public protocol DataSource {} /// /// Interface for a Get data source. /// public protocol GetDataSource: DataSource { - associatedtype T /// Get a single method @@ -38,12 +37,12 @@ public protocol GetDataSource: DataSource { func getAll(_ query: Query) -> Future<[T]> } -extension GetDataSource { - public func get(_ id: K) -> Future where K: Hashable { +public extension GetDataSource { + func get(_ id: K) -> Future where K: Hashable { return get(IdQuery(id)) } - public func getAll(_ id: K) -> Future<[T]> where K: Hashable { + func getAll(_ id: K) -> Future<[T]> where K: Hashable { return getAll(IdQuery(id)) } } @@ -52,32 +51,33 @@ extension GetDataSource { /// Interface for a Put data source. /// public protocol PutDataSource: DataSource { - associatedtype T /// Put by query method /// /// - Parameter query: An instance conforming to Query that encapsules the get query information - /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. id or timestamp fields. + /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. + // id or timestamp fields. @discardableResult func put(_ value: T?, in query: Query) -> Future /// Put by query method /// /// - Parameter query: An instance conforming to Query that encapsules the get query information - /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. id or timestamp fields. + /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. + // id or timestamp fields. @discardableResult func putAll(_ array: [T], in query: Query) -> Future<[T]> } -extension PutDataSource { +public extension PutDataSource { @discardableResult - public func put(_ value: T?, forId id: K) -> Future where K: Hashable { + func put(_ value: T?, forId id: K) -> Future where K: Hashable { return put(value, in: IdQuery(id)) } @discardableResult - public func putAll(_ array: [T], forId id: K) -> Future<[T]> where K: Hashable { + func putAll(_ array: [T], forId id: K) -> Future<[T]> where K: Hashable { return putAll(array, in: IdQuery(id)) } } @@ -97,20 +97,21 @@ public protocol DeleteDataSource: DataSource { /// /// - Parameter query: An instance conforming to Query that encapusles the delete query information /// - Returns: A future of Void type. - @available(*, deprecated, message: "Use delete with AllObjectsQuery to remove all entries or with any other Query to remove one or more entries") + @available(*, deprecated, + message: "Use delete with AllObjectsQuery to remove all entries or with any other Query to remove one or more entries") @discardableResult func deleteAll(_ query: Query) -> Future } -extension DeleteDataSource { +public extension DeleteDataSource { @discardableResult - public func delete(_ id: K) -> Future where K: Hashable { + func delete(_ id: K) -> Future where K: Hashable { return delete(IdQuery(id)) } @available(*, deprecated, message: "Use delete instead") @discardableResult - public func deleteAll(_ id: K) -> Future where K: Hashable { + func deleteAll(_ id: K) -> Future where K: Hashable { return deleteAll(IdQuery(id)) } } @@ -135,8 +136,11 @@ public enum DataSourceCRUD: CustomStringConvertible { } } -extension Query { - public func fatalError(_ method: DataSourceCRUD, _ origin: D) -> Never where D: DataSource { - Swift.fatalError("Undefined query \(String(describing: self)) for method \(method) on \(String(describing: type(of: origin)))") +public extension Query { + func fatalError(_ method: DataSourceCRUD, _ origin: D) -> Never where D: DataSource { + Swift + .fatalError( + "Undefined query \(String(describing: self)) for method \(method) on \(String(describing: type(of: origin)))" + ) } } diff --git a/Sources/Harmony/Data/DataSource/DataSourceAssembler.swift b/Sources/Harmony/Data/DataSource/DataSourceAssembler.swift index bdc5b671..89a7fb37 100644 --- a/Sources/Harmony/Data/DataSource/DataSourceAssembler.swift +++ b/Sources/Harmony/Data/DataSource/DataSourceAssembler.swift @@ -19,9 +19,13 @@ import Foundation /// /// Assambles a CRUD data source into a single data source object /// -public final class DataSourceAssembler : GetDataSource, PutDataSource, DeleteDataSource -where Get.T == T, Put.T == T { - +public final class DataSourceAssembler< + Get: GetDataSource, + Put: PutDataSource, + Delete: DeleteDataSource, + T +>: GetDataSource, PutDataSource, DeleteDataSource + where Get.T == T, Put.T == T { private let getDataSource: Get private let putDataSource: Put private let deleteDataSource: Delete @@ -67,68 +71,68 @@ where Get.T == T, Put.T == T { } } -extension DataSourceAssembler where Get == Put, Get == Delete { +public extension DataSourceAssembler where Get == Put, Get == Delete { /// Initializer for a single DataSource /// /// - Parameter dataSource: The data source - public convenience init(_ dataSource: Get) { + convenience init(_ dataSource: Get) { self.init(get: dataSource, put: dataSource, delete: dataSource) } } -extension DataSourceAssembler where Put == VoidPutDataSource, Delete == VoidDeleteDataSource { +public extension DataSourceAssembler where Put == VoidPutDataSource, Delete == VoidDeleteDataSource { /// Initializer for a single DataSource /// /// - Parameter getDataSource: The data source - public convenience init(get getDataSource: Get) { + convenience init(get getDataSource: Get) { self.init(get: getDataSource, put: VoidPutDataSource(), delete: VoidDeleteDataSource()) } } -extension DataSourceAssembler where Get == VoidGetDataSource, Delete == VoidDeleteDataSource { +public extension DataSourceAssembler where Get == VoidGetDataSource, Delete == VoidDeleteDataSource { /// Initializer for a single DataSource /// /// - Parameter putDataSource: The data source - public convenience init(put putDataSource: Put) { + convenience init(put putDataSource: Put) { self.init(get: VoidGetDataSource(), put: putDataSource, delete: VoidDeleteDataSource()) } } -extension DataSourceAssembler where Get == VoidGetDataSource, Put == VoidPutDataSource { +public extension DataSourceAssembler where Get == VoidGetDataSource, Put == VoidPutDataSource { /// Initializer for a single DataSource /// /// - Parameter deleteDataSource: The data source - public convenience init(delete deleteDataSource: Delete) { + convenience init(delete deleteDataSource: Delete) { self.init(get: VoidGetDataSource(), put: VoidPutDataSource(), delete: deleteDataSource) } } -extension DataSourceAssembler where Get == VoidGetDataSource { +public extension DataSourceAssembler where Get == VoidGetDataSource { /// Initializer for a single DataSource /// /// - Parameter putDataSource: The data source /// - Parameter deleteDataSource: The data source - public convenience init(put putDataSource: Put, delete deleteDataSource: Delete) { + convenience init(put putDataSource: Put, delete deleteDataSource: Delete) { self.init(get: VoidGetDataSource(), put: putDataSource, delete: deleteDataSource) } } -extension DataSourceAssembler where Put == VoidPutDataSource { +public extension DataSourceAssembler where Put == VoidPutDataSource { /// Initializer for a single DataSource /// /// - Parameter getDataSource: The data source /// - Parameter deleteDataSource: The data source - public convenience init(get getDataSource: Get, delete deleteDataSource: Delete) { + convenience init(get getDataSource: Get, delete deleteDataSource: Delete) { self.init(get: getDataSource, put: VoidPutDataSource(), delete: deleteDataSource) } } -extension DataSourceAssembler where Delete == VoidDeleteDataSource { +public extension DataSourceAssembler where Delete == VoidDeleteDataSource { /// Initializer for a single DataSource /// /// - Parameter getDataSource: The data source /// - Parameter putDataSource: The data source - public convenience init(get getDataSource: Get, put putDataSource: Put) { + convenience init(get getDataSource: Get, put putDataSource: Put) { self.init(get: getDataSource, put: putDataSource, delete: VoidDeleteDataSource()) } } diff --git a/Sources/Harmony/Data/DataSource/DataSourceValidator.swift b/Sources/Harmony/Data/DataSource/DataSourceValidator.swift index fa8ef117..1e797bda 100644 --- a/Sources/Harmony/Data/DataSource/DataSourceValidator.swift +++ b/Sources/Harmony/Data/DataSource/DataSourceValidator.swift @@ -21,9 +21,8 @@ import Foundation /// Note that validation only occur in the get and getAll methods. /// If not valid, the returned future is resolved with a ValidationError.notValid error /// -public class DataSourceValidator : GetDataSource, PutDataSource, DeleteDataSource -where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - +public class DataSourceValidator: GetDataSource, PutDataSource, DeleteDataSource + where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { private let dataSource: D private let validator: ObjectValidation diff --git a/Sources/Harmony/Data/DataSource/DebugDataSource.swift b/Sources/Harmony/Data/DataSource/DebugDataSource.swift index 67ffb855..60592f67 100644 --- a/Sources/Harmony/Data/DataSource/DebugDataSource.swift +++ b/Sources/Harmony/Data/DataSource/DebugDataSource.swift @@ -30,8 +30,8 @@ public enum DebugDataSourceError { switch self { case .none: break - case .error(let error, let probability): - if Double.random(in: 0.0...1.0) <= probability { + case let .error(error, probability): + if Double.random(in: 0.0 ... 1.0) <= probability { throw error } } @@ -39,7 +39,6 @@ public enum DebugDataSourceError { } private class DebugDataSourceToken { - let id: String = { let base = String(randomOfLength: 8) let seed = DispatchTime.now() @@ -61,13 +60,13 @@ private class DebugDataSourceToken { guard let start = startTime, let end = endTime else { return nil } - let seconds = TimeInterval((end.uptimeNanoseconds - start.uptimeNanoseconds)) / 1_000_000_000 + let seconds = TimeInterval(end.uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000_000 return seconds } } -public class DebugDataSource : GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - +public class DebugDataSource: GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, + D: PutDataSource, D: DeleteDataSource, D.T == T { private let dataSource: D private let delay: DebugDataSourceDelay private let error: DebugDataSourceError @@ -83,7 +82,8 @@ public class DebugDataSource : GetDataSource, PutDataSource, DeleteDataSo self.logger = logger } - private func postprocess(_ future: Future, _ method: DataSourceCRUD, _ token: DebugDataSourceToken) -> Future { + private func postprocess(_ future: Future, _ method: DataSourceCRUD, + _ token: DebugDataSourceToken) -> Future { return addError(addDelay(future.onCompletion { token.end() })).then { result in self.log(method, token, "Completed with result: \(String(describing: result))") }.fail { error in @@ -95,9 +95,9 @@ public class DebugDataSource : GetDataSource, PutDataSource, DeleteDataSo switch delay { case .none: return future - case .sync(let delay): + case let .sync(delay): return future.withBlockingDelay(delay) - case .async(let delay, let queue): + case let .async(delay, queue): return future.withDelay(delay, queue: queue) } } @@ -108,7 +108,10 @@ public class DebugDataSource : GetDataSource, PutDataSource, DeleteDataSo private func log(_ method: DataSourceCRUD, _ token: DebugDataSourceToken, _ message: String) { if let time = token.time() { - logger.info(tag: String(describing: type(of: dataSource)), "[\(method).\(token.id) in <\(time)>s]: \(message)") + logger.info( + tag: String(describing: type(of: dataSource)), + "[\(method).\(token.id) in <\(time)>s]: \(message)" + ) } else { logger.info(tag: String(describing: type(of: dataSource)), "[\(method).\(token.id)]: \(message)") } diff --git a/Sources/Harmony/Data/DataSource/DeviceStorageDataSource.swift b/Sources/Harmony/Data/DataSource/DeviceStorageDataSource.swift index 0df2da9a..17d0b0b2 100644 --- a/Sources/Harmony/Data/DataSource/DeviceStorageDataSource.swift +++ b/Sources/Harmony/Data/DataSource/DeviceStorageDataSource.swift @@ -23,7 +23,7 @@ public enum DeviceStorageType { fileprivate func key(_ key: String) -> String { switch self { - case .prefix(let prefix): + case let .prefix(prefix): switch prefix.count { case 0: return key @@ -36,8 +36,7 @@ public enum DeviceStorageType { } } -public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteDataSource { - +public class DeviceStorageDataSource: GetDataSource, PutDataSource, DeleteDataSource { private let userDefaults: UserDefaults private let storageType: DeviceStorageType @@ -48,12 +47,12 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD public init(_ userDefaults: UserDefaults = UserDefaults.standard, prefix: String) { self.userDefaults = userDefaults - self.storageType = .prefix(prefix) + storageType = .prefix(prefix) } private func getRootKey() -> String? { switch storageType { - case .rootKey(let rootKey): + case let .rootKey(rootKey): return "\(rootKey)<\(String(describing: T.self))>" default: return nil @@ -65,7 +64,6 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD case let query as KeyQuery: let key = storageType.key(query.key) guard let value: T = { - if let rootKey = getRootKey() { return userDefaults.dictionary(forKey: rootKey)?[key] as? T } @@ -99,7 +97,7 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD // Dict can be composed of components of type T or [T]. // Let's add it all together in an array. var array = [T]() - dict.forEach { (_, value) in + dict.forEach { _, value in if let value = value as? T { array.append(value) } else if let values = value as? [T] { @@ -109,9 +107,9 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD } } return Future(array) - case .prefix(let prefix): + case let .prefix(prefix): var array = [T]() - userDefaults.dictionaryRepresentation().forEach { (key, value) in + userDefaults.dictionaryRepresentation().forEach { key, value in // Let's search for keys with the given prefix guard key.hasPrefix(prefix) else { return } @@ -195,7 +193,7 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD public func delete(_ query: Query) -> Future { switch query { case let query as IdsQuery: - return Future.batch(query.ids.map { delete(IdQuery($0)) }).map { _ in Void() } + return Future.batch(query.ids.map { delete(IdQuery($0)) }).map { _ in () } case is AllObjectsQuery: switch storageType { case .regular: @@ -204,9 +202,9 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD let rootKey = getRootKey()! // Will always be present in this case userDefaults.removeObject(forKey: rootKey) userDefaults.synchronize() - return Future(Void()) - case .prefix(let prefix): - userDefaults.dictionaryRepresentation().forEach { (key, value) in + return Future(()) + case let .prefix(prefix): + userDefaults.dictionaryRepresentation().forEach { key, value in // Let's search for keys with the given prefix guard key.hasPrefix(prefix) else { return } @@ -220,7 +218,7 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD // Ignore the value as its type doesn't match } } - return Future(Void()) + return Future(()) } case let query as KeyQuery: let key = storageType.key(query.key) @@ -232,7 +230,7 @@ public class DeviceStorageDataSource : GetDataSource, PutDataSource, DeleteD userDefaults.removeObject(forKey: key) } userDefaults.synchronize() - return Future(Void()) + return Future(()) default: query.fatalError(.delete, self) } diff --git a/Sources/Harmony/Data/DataSource/FileSystemStorageDataSource.swift b/Sources/Harmony/Data/DataSource/FileSystemStorageDataSource.swift index 8828ecec..86261ca5 100644 --- a/Sources/Harmony/Data/DataSource/FileSystemStorageDataSource.swift +++ b/Sources/Harmony/Data/DataSource/FileSystemStorageDataSource.swift @@ -44,7 +44,12 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa /// - Parameters: /// - fileManager: The FileManager /// - directory: The directory where to store data - public init(fileManager: FileManager, directory: URL, writingOptions: Data.WritingOptions = [], fileNameEncoding: FileNameEncoding = .sha256) { + public init( + fileManager: FileManager, + directory: URL, + writingOptions: Data.WritingOptions = [], + fileNameEncoding: FileNameEncoding = .sha256 + ) { self.fileManager = fileManager self.directory = directory self.writingOptions = writingOptions @@ -54,14 +59,25 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa /// Convenience initializer. Returns nil if the document directory is not reachable. /// /// - Parameters: - /// - relativePath: The relative path (example: "MyFolder/MySubfolder"), that will be appended on the documents directory - public convenience init?(fileManager: FileManager, relativePath: String, writingOptions: Data.WritingOptions = [], fileNameEncoding: FileNameEncoding = .sha256) { + /// - relativePath: The relative path (example: "MyFolder/MySubfolder"), that will be appended on the + // documents directory + public convenience init?( + fileManager: FileManager, + relativePath: String, + writingOptions: Data.WritingOptions = [], + fileNameEncoding: FileNameEncoding = .sha256 + ) { guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } let url = documentsURL.appendingPathComponent(relativePath) print(url) - self.init(fileManager: fileManager, directory: url, writingOptions: writingOptions, fileNameEncoding: fileNameEncoding) + self.init( + fileManager: fileManager, + directory: url, + writingOptions: writingOptions, + fileNameEncoding: fileNameEncoding + ) } private func fileName(_ key: String) -> String { @@ -72,7 +88,7 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa return key.sha256() case .md5: return key.md5() - case .custom(let encoder): + case let .custom(encoder): return encoder(key) } } @@ -112,13 +128,16 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa .contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey]) .filter { url in // Filter out folders - do { return !(try url.resourceValues(forKeys: [.isDirectoryKey])).isDirectory! } catch { return false } + do { return !(try url.resourceValues(forKeys: [.isDirectoryKey])).isDirectory! } catch { + return false + } }.forEach { url in guard let data = fileManager.contents(atPath: url.path) else { throw CoreError.NotFound("Data not found at path: \(url.path)") } // Attempting to unarchive in case it was an array - // if let datas = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, NSData.self], from: data) as? [Data] { + // if let datas = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: + // [NSArray.self, NSData.self], from: data) as? [Data] { if let datas = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Data] { // it was an array! array.append(contentsOf: datas) @@ -134,7 +153,8 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa guard let data = fileManager.contents(atPath: path) else { return Future(CoreError.NotFound("Data not found at path: \(path)")) } - // guard let array = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, NSData.self], from: data) as? [Data] else { + // guard let array = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, + // NSData.self], from: data) as? [Data] else { guard let array = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Data] else { return Future(CoreError.NotFound("Data not found at path: \(path)")) } @@ -155,7 +175,11 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa let fileURL = self.fileURL(keyQuery.key) let folderURL = fileURL.deletingLastPathComponent() if fileManager.fileExists(atPath: folderURL.path) == false { - try fileManager.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil) + try fileManager.createDirectory( + atPath: folderURL.path, + withIntermediateDirectories: true, + attributes: nil + ) } try data.write(to: fileURL, options: writingOptions) r.set(data) @@ -169,11 +193,15 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa query.fatalError(.putAll, self) } return Future { r in - try query.ids.enumerated().forEach { (offset, id) in + try query.ids.enumerated().forEach { offset, id in let fileURL = self.fileURL(id) let folderURL = fileURL.deletingLastPathComponent() if fileManager.fileExists(atPath: folderURL.path) == false { - try fileManager.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil) + try fileManager.createDirectory( + atPath: folderURL.path, + withIntermediateDirectories: true, + attributes: nil + ) } try array[offset].write(to: fileURL, options: writingOptions) } @@ -184,29 +212,32 @@ public class FileSystemStorageDataSource: GetDataSource, PutDataSource, DeleteDa let fileURL = self.fileURL(query.key) let folderURL = fileURL.deletingLastPathComponent() if fileManager.fileExists(atPath: folderURL.path) == false { - try fileManager.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil) + try fileManager.createDirectory( + atPath: folderURL.path, + withIntermediateDirectories: true, + attributes: nil + ) } - // let data = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: false) + // let data = try NSKeyedArchiver.archivedData(withRootObject: array, + // requiringSecureCoding: false) let data = NSKeyedArchiver.archivedData(withRootObject: array) try data.write(to: fileURL, options: writingOptions) r.set(array) } default: query.fatalError(.getAll, self) - } - } public func delete(_ query: Query) -> Future { switch query { case let query as IdsQuery: let futures: [Future] = query.ids.map { id in - return Future { + Future { try? fileManager.removeItem(at: fileURL(id)) } } - return Future.batch(futures).map { _ in Void() } + return Future.batch(futures).map { _ in () } case is AllObjectsQuery: return Future { // Deleting everything! diff --git a/Sources/Harmony/Data/DataSource/InMemoryDataSource.swift b/Sources/Harmony/Data/DataSource/InMemoryDataSource.swift index ec60d0aa..3997e3b0 100644 --- a/Sources/Harmony/Data/DataSource/InMemoryDataSource.swift +++ b/Sources/Harmony/Data/DataSource/InMemoryDataSource.swift @@ -17,7 +17,6 @@ import Foundation public class InMemoryDataSource: GetDataSource, PutDataSource, DeleteDataSource { - private var objects: [String: T] = [:] private var arrays: [String: [T]] = [:] @@ -77,7 +76,7 @@ public class InMemoryDataSource: GetDataSource, PutDataSource, DeleteDataSour guard array.count == query.ids.count else { return Future(CoreError.IllegalArgument("Array lenght must be equal to query.ids length")) } - array.enumerated().forEach { (offset, element) in + array.enumerated().forEach { offset, element in arrays.removeValue(forKey: query.ids[offset]) objects[query.ids[offset]] = element } @@ -97,15 +96,15 @@ public class InMemoryDataSource: GetDataSource, PutDataSource, DeleteDataSour case is AllObjectsQuery: objects.removeAll() arrays.removeAll() - return Future(Void()) + return Future(()) case let query as IdsQuery: query.ids.forEach { key in clearAll(key: key) } - return Future(Void()) + return Future(()) case let query as KeyQuery: clearAll(key: query.key) - return Future(Void()) + return Future(()) default: return Future(CoreError.QueryNotSupported()) } diff --git a/Sources/Harmony/Data/DataSource/RetryDataSource.swift b/Sources/Harmony/Data/DataSource/RetryDataSource.swift index 4616e820..4961a0af 100644 --- a/Sources/Harmony/Data/DataSource/RetryDataSource.swift +++ b/Sources/Harmony/Data/DataSource/RetryDataSource.swift @@ -19,8 +19,8 @@ import Foundation /// /// A retry data source adds retry capabilities over an existing data source. /// -public class RetryDataSource : GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - +public class RetryDataSource: GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, + D: PutDataSource, D: DeleteDataSource, D.T == T { private let dataSource: D private let retryCount: Int private let retryIf: (Error) -> Bool @@ -30,10 +30,11 @@ public class RetryDataSource : GetDataSource, PutDataSource, DeleteDataSo /// - Parameters: /// - dataSource: The data source to retry /// - retryCount: The number of retries. Default value is 1. - /// - retryIf: A closure to evaluate each retry error. Return true to allow a retry, false otherwise. Default closure returns true. + /// - retryIf: A closure to evaluate each retry error. Return true to allow a retry, false otherwise. Default + // closure returns true. public init(_ dataSource: D, retryCount: Int = 1, - retryIf : @escaping (Error) -> Bool = { _ in true }) { + retryIf: @escaping (Error) -> Bool = { _ in true }) { self.dataSource = dataSource self.retryCount = retryCount self.retryIf = retryIf @@ -69,12 +70,11 @@ public class RetryDataSource : GetDataSource, PutDataSource, DeleteDataSo } extension RetryDataSource { - private func retry(_ it: Int, _ error: Error, _ closure: () -> Future) -> Future { // Must retry if: // - it is greater than zero // - The retryIf closure returns true - if it > 0 && retryIf(error) { + if it > 0, retryIf(error) { return closure() } return Future(error) @@ -82,48 +82,48 @@ extension RetryDataSource { private func get(_ query: Query, _ it: Int) -> Future { return dataSource.get(query).recover { error in - return self.retry(it, error) { - return self.get(query, it - 1) + self.retry(it, error) { + self.get(query, it - 1) } } } private func getAll(_ query: Query, _ it: Int) -> Future<[T]> { return dataSource.getAll(query).recover { error in - return self.retry(it, error) { - return self.getAll(query, it - 1) + self.retry(it, error) { + self.getAll(query, it - 1) } } } private func put(_ value: T?, in query: Query, _ it: Int) -> Future { return dataSource.put(value, in: query).recover { error in - return self.retry(it, error) { - return self.put(value, in: query, it - 1) + self.retry(it, error) { + self.put(value, in: query, it - 1) } } } private func putAll(_ array: [T], in query: Query, _ it: Int) -> Future<[T]> { return dataSource.putAll(array, in: query).recover { error in - return self.retry(it, error) { - return self.putAll(array, in: query, it - 1) + self.retry(it, error) { + self.putAll(array, in: query, it - 1) } } } private func delete(_ query: Query, _ it: Int) -> Future { return dataSource.delete(query).recover { error in - return self.retry(it, error) { - return self.delete(query, it - 1) + self.retry(it, error) { + self.delete(query, it - 1) } } } private func deleteAll(_ query: Query, _ it: Int) -> Future { return dataSource.deleteAll(query).recover { error in - return self.retry(it, error) { - return self.deleteAll(query, it - 1) + self.retry(it, error) { + self.deleteAll(query, it - 1) } } } diff --git a/Sources/Harmony/Data/DataSource/TimedCacheDataSource.swift b/Sources/Harmony/Data/DataSource/TimedCacheDataSource.swift index ead7ceef..aca60cd6 100644 --- a/Sources/Harmony/Data/DataSource/TimedCacheDataSource.swift +++ b/Sources/Harmony/Data/DataSource/TimedCacheDataSource.swift @@ -18,22 +18,22 @@ import Foundation private func print(_ object: String) { #if DEBUG - Swift.print(object) + Swift.print(object) #endif } /// -/// The TimedCacheDataSource is KeyQuery-based data source, wrapper of another data source and acting as a fast cache. +/// The TimedCacheDataSource is KeyQuery-based data source, wrapper of another data source and acting as a fast +// cache. /// It uses the date time of the access to cache the values, acting as a TLRU cache. /// public class TimedCacheDataSource: GetDataSource, PutDataSource, DeleteDataSource -where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - + where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { private let dataSource: D private let expiryInterval: TimeInterval - private var objects: [String : (object: T, date: Date)] = [:] - private var arrays: [String : (array: [T], date: Date)] = [:] + private var objects: [String: (object: T, date: Date)] = [:] + private var arrays: [String: (array: [T], date: Date)] = [:] /// Default initializer /// @@ -61,7 +61,9 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { self.objects[query.key] = nil } default: - print("TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).get call because \(type(of: query)) doesn't conform to KeyQuery.") + print( + "TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).get call because \(type(of: query)) doesn't conform to KeyQuery." + ) return dataSource.get(query) } } @@ -79,7 +81,7 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { } default: print("TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).getAll call " + - "because \(type(of: query)) doesn't conform to KeyQuery.") + "because \(type(of: query)) doesn't conform to KeyQuery.") return dataSource.getAll(query) } } @@ -89,13 +91,15 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { switch query { case let query as KeyQuery: return dataSource.put(value, in: query).then { object in - self.arrays[query.key] = nil + self.arrays[query.key] = nil self.objects[query.key] = (object, Date()) }.fail { _ in self.objects[query.key] = nil } default: - print("TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).put call because \(type(of: query)) doesn't conform to KeyQuery.") + print( + "TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).put call because \(type(of: query)) doesn't conform to KeyQuery." + ) return dataSource.put(value, in: query) } } @@ -112,7 +116,7 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { } default: print("TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).putAll " + - "call because \(type(of: query)) doesn't conform to KeyQuery.") + "call because \(type(of: query)) doesn't conform to KeyQuery.") return dataSource.putAll(array, in: query) } } @@ -127,7 +131,7 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { } default: print("TimedCacheDataSource can't cache the result of the \(type(of: dataSource)).delete call " + - "because \(type(of: query)) doesn't conform to KeyQuery.") + "because \(type(of: query)) doesn't conform to KeyQuery.") return dataSource.delete(query) } } diff --git a/Sources/Harmony/Data/DataSource/VoidDataSource.swift b/Sources/Harmony/Data/DataSource/VoidDataSource.swift index 34f16def..ed571ef3 100644 --- a/Sources/Harmony/Data/DataSource/VoidDataSource.swift +++ b/Sources/Harmony/Data/DataSource/VoidDataSource.swift @@ -20,38 +20,38 @@ import Foundation /// Void get data source implementation /// public class VoidGetDataSource: GetDataSource { - public init() { } - public func get(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func getAll(_ query: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public init() {} + public func get(_: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func getAll(_: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } } /// /// Void put data source implementation /// public class VoidPutDataSource: PutDataSource { - public init() { } - public func put(_ value: T?, in query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func putAll(_ array: [T], in query: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public init() {} + public func put(_: T?, in _: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func putAll(_: [T], in _: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } } /// /// Void delete data source implementation /// public class VoidDeleteDataSource: DeleteDataSource { - public init() { } - public func delete(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func deleteAll(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } + public init() {} + public func delete(_: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func deleteAll(_: Query) -> Future { return Future(CoreError.NotImplemented()) } } /// /// Void data source implementation /// public class VoidDataSource: GetDataSource, PutDataSource, DeleteDataSource { - public init() { } - public func get(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func getAll(_ query: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } - public func put(_ value: T?, in query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func putAll(_ array: [T], in query: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } - public func delete(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } - public func deleteAll(_ query: Query) -> Future { return Future(CoreError.NotImplemented()) } + public init() {} + public func get(_: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func getAll(_: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public func put(_: T?, in _: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func putAll(_: [T], in _: Query) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public func delete(_: Query) -> Future { return Future(CoreError.NotImplemented()) } + public func deleteAll(_: Query) -> Future { return Future(CoreError.NotImplemented()) } } diff --git a/Sources/Harmony/Data/Mapper/DataSourceMapper.swift b/Sources/Harmony/Data/Mapper/DataSourceMapper.swift index 1c8df2a4..b1562e18 100644 --- a/Sources/Harmony/Data/Mapper/DataSourceMapper.swift +++ b/Sources/Harmony/Data/Mapper/DataSourceMapper.swift @@ -17,10 +17,10 @@ import Foundation /// -/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple "translator". +/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple +// "translator". /// -public class GetDataSourceMapper : GetDataSource where D.T == In { - +public class GetDataSourceMapper: GetDataSource where D.T == In { public typealias T = Out private let dataSource: D @@ -39,7 +39,7 @@ public class GetDataSourceMapper : GetDataSource whe public func get(_ query: Query) -> Future { return dataSource.get(query).map { value in - return try self.toOutMapper.map(value) + try self.toOutMapper.map(value) } } @@ -55,10 +55,10 @@ extension GetDataSource { } /// -/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple "translator". +/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple +// "translator". /// -public class PutDataSourceMapper : PutDataSource where D.T == In { - +public class PutDataSourceMapper: PutDataSource where D.T == In { public typealias T = Out private let dataSource: D @@ -92,22 +92,25 @@ public class PutDataSourceMapper : PutDataSource whe @discardableResult public func putAll(_ array: [Out], in query: Query) -> Future<[Out]> { - return Future { dataSource.putAll(try toInMapper.map(array), in: query).map { try self.toOutMapper.map($0) } } + return Future { + dataSource.putAll(try toInMapper.map(array), in: query).map { try self.toOutMapper.map($0) } + } } } extension PutDataSource { - func withMapping(in toInMapper: Mapper, out toOutMapper: Mapper) -> PutDataSourceMapper { + func withMapping(in toInMapper: Mapper, + out toOutMapper: Mapper) -> PutDataSourceMapper { return PutDataSourceMapper(dataSource: self, toInMapper: toInMapper, toOutMapper: toOutMapper) } } /// -/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple "translator". +/// This data source uses mappers to map objects and redirects them to the contained data source, acting as a simple +// "translator". /// -public class DataSourceMapper : GetDataSource, PutDataSource, DeleteDataSource -where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == In { - +public class DataSourceMapper: GetDataSource, PutDataSource, DeleteDataSource + where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == In { public typealias T = Out private let dataSource: D @@ -130,7 +133,7 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == In { public func get(_ query: Query) -> Future { return dataSource.get(query).map { value in - return try self.toOutMapper.map(value) + try self.toOutMapper.map(value) } } @@ -151,7 +154,9 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == In { @discardableResult public func putAll(_ array: [Out], in query: Query) -> Future<[Out]> { - return Future { dataSource.putAll(try toInMapper.map(array), in: query).map { try self.toOutMapper.map($0) } } + return Future { + dataSource.putAll(try toInMapper.map(array), in: query).map { try self.toOutMapper.map($0) } + } } @discardableResult diff --git a/Sources/Harmony/Data/Mapper/Mapper+Codable.swift b/Sources/Harmony/Data/Mapper/Mapper+Codable.swift index ee1fc2b1..2c019e48 100644 --- a/Sources/Harmony/Data/Mapper/Mapper+Codable.swift +++ b/Sources/Harmony/Data/Mapper/Mapper+Codable.swift @@ -16,14 +16,14 @@ import Foundation -public class EncodableToDataMapper : Mapper where T: Encodable { +public class EncodableToDataMapper: Mapper where T: Encodable { private let mapping: [String: String] public init(_ mapping: [String: String] = [:]) { self.mapping = mapping } - public override func map(_ from: T) -> Data { + override public func map(_ from: T) -> Data { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .map(mapping) let data = try! encoder.encode(from) @@ -31,14 +31,14 @@ public class EncodableToDataMapper : Mapper where T: Encodable { } } -public class DataToDecodableMapper : Mapper where T: Decodable { +public class DataToDecodableMapper: Mapper where T: Decodable { private let mapping: [String: String] public init(_ mapping: [String: String] = [:]) { self.mapping = mapping } - public override func map(_ from: Data) -> T { + override public func map(_ from: Data) -> T { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .map(mapping) let value = try! decoder.decode(T.self, from: from) @@ -46,15 +46,14 @@ public class DataToDecodableMapper : Mapper where T: Decodable { } } -public class EncodableToDecodableMapper : Mapper where D: Decodable, E: Encodable { - +public class EncodableToDecodableMapper: Mapper where D: Decodable, E: Encodable { private let mapping: [String: String] public init(_ mapping: [String: String] = [:]) { self.mapping = mapping } - public override func map(_ from: E) -> D { + override public func map(_ from: E) -> D { let encoder = JSONEncoder() // Encoding to a format that is readable by the decoder encoder.keyEncodingStrategy = .map(mapping) diff --git a/Sources/Harmony/Data/Mapper/Mapper+NSCoding.swift b/Sources/Harmony/Data/Mapper/Mapper+NSCoding.swift index 3222705d..4d796951 100644 --- a/Sources/Harmony/Data/Mapper/Mapper+NSCoding.swift +++ b/Sources/Harmony/Data/Mapper/Mapper+NSCoding.swift @@ -16,15 +16,15 @@ import Foundation -public class NSCodingToDataMapper : Mapper { - public override func map(_ from: T) -> Data { +public class NSCodingToDataMapper: Mapper { + override public func map(_ from: T) -> Data { // return try! NSKeyedArchiver.archivedData(withRootObject: from, requiringSecureCoding: false) return NSKeyedArchiver.archivedData(withRootObject: from) } } -public class DataToNSCodingMapper : Mapper { // where T:NSObject { - public override func map(_ from: Data) -> T { +public class DataToNSCodingMapper: Mapper { // where T:NSObject { + override public func map(_ from: Data) -> T { // return try! NSKeyedUnarchiver.unarchivedObject(ofClass: T.self, from: from)! return NSKeyedUnarchiver.unarchiveObject(with: from) as! T } diff --git a/Sources/Harmony/Data/Mapper/Mapper.swift b/Sources/Harmony/Data/Mapper/Mapper.swift index bd1b101d..76831005 100644 --- a/Sources/Harmony/Data/Mapper/Mapper.swift +++ b/Sources/Harmony/Data/Mapper/Mapper.swift @@ -19,28 +19,27 @@ import Foundation /// /// Abstract class to map an object type to another object type /// -open class Mapper { - +open class Mapper { /// Default initializer - public init() { } + public init() {} /// Mapping method /// /// - Parameter from: The original object /// - Returns: The new mapped object /// - Throws: Mapping error. Typically of type CoreError.Failed - open func map(_ from: From) throws -> To { + open func map(_: From) throws -> To { fatalError("Undefined mapper. Class Mapper must be subclassed.") } } -extension Mapper { +public extension Mapper { /// Mapping method for arrays /// /// - Parameter array: An array of objects /// - Returns: An array of mapped objects /// - Throws: Mapping error. Typically of type CoreError.Failed - public func map(_ array: [From]) throws -> [To] { + func map(_ array: [From]) throws -> [To] { return try array.map { try map($0) } } @@ -49,18 +48,18 @@ extension Mapper { /// - Parameter dictionary: A dictionary of key-value, where value is typed as "From" /// - Returns: A dictionary of mapped values /// - Throws: Mapping error. Typically of type CoreError.Failed - public func map(_ dictionary: [K: From]) throws -> [K: To] { + func map(_ dictionary: [K: From]) throws -> [K: To] { return try dictionary.mapValues { try map($0) } } } -extension Mapper where From: Hashable, To: Hashable { +public extension Mapper where From: Hashable, To: Hashable { /// Mapping method for sets /// /// - Parameter set: A set to be mapped /// - Returns: A mapped set /// - Throws: Mapping error. Typically of type CoreError.Failed - public func map(_ set: Set) throws -> Set { + func map(_ set: Set) throws -> Set { return Set(try set.map { try map($0) }) } } @@ -68,8 +67,8 @@ extension Mapper where From: Hashable, To: Hashable { /// /// VoidMapper throws a CoreError.NotImplemented /// -public class VoidMapper : Mapper { - public override func map(_ from: From) throws -> To { +public class VoidMapper: Mapper { + override public func map(_: From) throws -> To { throw CoreError.NotImplemented() } } @@ -77,7 +76,7 @@ public class VoidMapper : Mapper { /// /// A mock mapper returns the mock object when mapping any object. /// -public class MockMapper : Mapper { +public class MockMapper: Mapper { private let mock: To /// Default initializer @@ -87,7 +86,7 @@ public class MockMapper : Mapper { self.mock = mock } - public override func map(_ from: From) throws -> To { + override public func map(_: From) throws -> To { return mock } } @@ -95,8 +94,8 @@ public class MockMapper : Mapper { /// /// IdentityMapper returns the same value /// -public class IdentityMapper : Mapper { - public override func map(_ from: T) throws -> T { +public class IdentityMapper: Mapper { + override public func map(_ from: T) throws -> T { return from } } @@ -104,10 +103,13 @@ public class IdentityMapper : Mapper { /// /// CastMapper tries to casts the input value to the mapped type. Otherwise, throws an CoreError.Failed error. /// -public class CastMapper : Mapper { - public override func map(_ from: From) throws -> To { +public class CastMapper: Mapper { + override public func map(_ from: From) throws -> To { guard let to = from as? To else { - throw CoreError.Failed("CastMapper failed to map an object of type \(type(of: from)) to \(String(describing: To.self))") + throw CoreError + .Failed( + "CastMapper failed to map an object of type \(type(of: from)) to \(String(describing: To.self))" + ) } return to } @@ -116,19 +118,18 @@ public class CastMapper : Mapper { /// /// Mapper defined by a closure /// -public class ClosureMapper : Mapper { - +public class ClosureMapper: Mapper { private let closure: (From) throws -> To /// Default initializer /// /// - Parameter closure: The map closure - public init (_ closure : @escaping (From) throws -> To) { + public init(_ closure: @escaping (From) throws -> To) { self.closure = closure super.init() } - public override func map(_ from: From) throws -> To { + override public func map(_ from: From) throws -> To { return try closure(from) } } @@ -136,22 +137,21 @@ public class ClosureMapper : Mapper { /// /// Composes a two mappers A->B & B->C to create a mapper A->C. /// -public class ComposedMapper : Mapper { - - private let mapperAB: Mapper - private let mapperBC: Mapper +public class ComposedMapper: Mapper { + private let mapperAB: Mapper + private let mapperBC: Mapper /// Default initializer /// /// - Parameters: /// - mapperAB: Mapper A->B /// - mapperBC: Mapper B->C - public init(_ mapperAB: Mapper , _ mapperBC: Mapper) { + public init(_ mapperAB: Mapper, _ mapperBC: Mapper) { self.mapperAB = mapperAB self.mapperBC = mapperBC } - public override func map(_ from: A) throws -> C { + override public func map(_ from: A) throws -> C { return try mapperBC.map(try mapperAB.map(from)) } } @@ -161,8 +161,8 @@ public class ComposedMapper : Mapper { /// /// Converts Data into a base64 encoded string /// -public class DataToBase64StringMapper: Mapper { - public override func map(_ from: Data) throws -> String { +public class DataToBase64StringMapper: Mapper { + override public func map(_ from: Data) throws -> String { return from.base64EncodedString() } } @@ -171,8 +171,8 @@ public class DataToBase64StringMapper: Mapper { /// Converts base64 encoded string to data. /// Throws CoreError.Failed if string is invalid. /// -public class Base64StringToDataMapper: Mapper { - public override func map(_ from: String) throws -> Data { +public class Base64StringToDataMapper: Mapper { + override public func map(_ from: String) throws -> Data { guard let data = Data(base64Encoded: from) else { throw CoreError.Failed("Failed to map String into Data.") } @@ -183,8 +183,8 @@ public class Base64StringToDataMapper: Mapper { /// /// Converts Data into a hexadecimal encoded string /// -public class DataToHexStringMapper: Mapper { - public override func map(_ from: Data) throws -> String { +public class DataToHexStringMapper: Mapper { + override public func map(_ from: Data) throws -> String { return from.hexEncodedString() } } @@ -193,8 +193,8 @@ public class DataToHexStringMapper: Mapper { /// Converts hexadecimal encoded string to data. /// Throws CoreError.Failed if string is invalid. /// -public class HexStringToDataMapper: Mapper { - public override func map(_ from: String) throws -> Data { +public class HexStringToDataMapper: Mapper { + override public func map(_ from: String) throws -> Data { guard let data = Data(hexEncoded: from) else { throw CoreError.Failed("Failed to map String into Data.") } diff --git a/Sources/Harmony/Data/Operation/Operation.swift b/Sources/Harmony/Data/Operation/Operation.swift index 47f77d29..6724c05f 100644 --- a/Sources/Harmony/Data/Operation/Operation.swift +++ b/Sources/Harmony/Data/Operation/Operation.swift @@ -17,13 +17,14 @@ import Foundation /// -/// An operation defines an abstraction on how data must be fetched (how and to which data source a query must be forwarded). +/// An operation defines an abstraction on how data must be fetched (how and to which data source a query must be +// forwarded). /// -public protocol Operation { } +public protocol Operation {} /// /// The default operation. All repository implementations must accept this operation. /// public class DefaultOperation: Operation { - public init() { } + public init() {} } diff --git a/Sources/Harmony/Data/Query/Query.swift b/Sources/Harmony/Data/Query/Query.swift index 2211a42d..bac85792 100644 --- a/Sources/Harmony/Data/Query/Query.swift +++ b/Sources/Harmony/Data/Query/Query.swift @@ -19,7 +19,7 @@ import Foundation /// /// Default query interface /// -public protocol Query { } +public protocol Query {} /// Protocol to use a query as a key for a key value interface public protocol KeyQuery: Query { @@ -29,7 +29,7 @@ public protocol KeyQuery: Query { /// Void query public class VoidQuery: Query { - public init() { } + public init() {} } /// A query by an id @@ -38,16 +38,15 @@ open class IdQuery: Query, KeyQuery where T: Hashable { public init(_ id: T) { self.id = id } + public var key: String { - get { - switch T.self { - case is String.Type: - return id as! String - case is Int.Type: - return "\(id as! Int)" - default: - return "\(id.hashValue)" - } + switch T.self { + case is String.Type: + return id as! String + case is Int.Type: + return "\(id as! Int)" + default: + return "\(id.hashValue)" } } } @@ -62,7 +61,7 @@ open class IdsQuery: Query where T: Hashable { /// All objects query public class AllObjectsQuery: Query, KeyQuery { - public init() { } + public init() {} public var key: String { return "allObjects" } } @@ -90,7 +89,7 @@ public class ObjectsQuery: Query { } /// Abstract pagination query -open class PaginationQuery: Query { } +open class PaginationQuery: Query {} /// Pagination by offset and limit open class PaginationOffsetLimitQuery: PaginationQuery { diff --git a/Sources/Harmony/Data/Repository/AnyGetRepository.swift b/Sources/Harmony/Data/Repository/AnyGetRepository.swift index a31e4c86..46fea76f 100644 --- a/Sources/Harmony/Data/Repository/AnyGetRepository.swift +++ b/Sources/Harmony/Data/Repository/AnyGetRepository.swift @@ -19,8 +19,7 @@ import Foundation /// /// A type eraser for the GetRepository type, following Apple's Swift Standard Library approach. /// -public final class AnyGetRepository : GetRepository { - +public final class AnyGetRepository: GetRepository { private let box: GetRepositoryBoxBase /// Default initializer. @@ -40,11 +39,11 @@ public final class AnyGetRepository : GetRepository { } } -extension GetRepository { +public extension GetRepository { /// Returns an AnyGetRepository abstraction of the current repository /// /// - Returns: An AnyGetRepository abstraction - public func asAnyGetRepository() -> AnyGetRepository { + func asAnyGetRepository() -> AnyGetRepository { if let repo = self as? AnyGetRepository { return repo } @@ -54,24 +53,24 @@ extension GetRepository { /// /// This is an abstract class. Do not use it. -/// GetRepository base class defining a generic type T (which is unrelated to the associated type of the GetRepository protocol) +/// GetRepository base class defining a generic type T (which is unrelated to the associated type of the +// GetRepository protocol) /// -internal class GetRepositoryBoxBase : GetRepository { - - func get(_ query: Query, operation: Operation) -> Future { +internal class GetRepositoryBoxBase: GetRepository { + func get(_: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } - func getAll(_ query: Query, operation: Operation) -> Future<[T]> { + func getAll(_: Query, operation _: Operation) -> Future<[T]> { fatalError("This method is abstract.") } } /// -/// A repository box, which has as generic type a GetRepository and links the GetRepositoryBoxBase type T as the Base.T type. +/// A repository box, which has as generic type a GetRepository and links the GetRepositoryBoxBase type T as the +// Base.T type. /// -internal class GetRepositoryBox : GetRepositoryBoxBase { - +internal class GetRepositoryBox: GetRepositoryBoxBase { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/Repository/AnyPutRepository.swift b/Sources/Harmony/Data/Repository/AnyPutRepository.swift index 07f55f54..f8f31143 100644 --- a/Sources/Harmony/Data/Repository/AnyPutRepository.swift +++ b/Sources/Harmony/Data/Repository/AnyPutRepository.swift @@ -19,8 +19,7 @@ import Foundation /// /// A type eraser for the PutRepository type, following Apple's Swift Standard Library approach. /// -public final class AnyPutRepository : PutRepository { - +public final class AnyPutRepository: PutRepository { private let box: PutRepositoryBoxBase /// Default initializer. @@ -40,11 +39,11 @@ public final class AnyPutRepository : PutRepository { } } -extension PutRepository { +public extension PutRepository { /// Returns an AnyPutRepository abstraction of the current repository /// /// - Returns: An AnyPutRepository abstraction - public func asAnyPutRepository() -> AnyPutRepository { + func asAnyPutRepository() -> AnyPutRepository { if let repo = self as? AnyPutRepository { return repo } @@ -54,24 +53,24 @@ extension PutRepository { /// /// This is an abstract class. Do not use it. -/// PutRepository base class defining a generic type T (which is unrelated to the associated type of the PutRepository protocol) +/// PutRepository base class defining a generic type T (which is unrelated to the associated type of the +// PutRepository protocol) /// -internal class PutRepositoryBoxBase : PutRepository { - - func put(_ value: T?, in query: Query, operation: Operation) -> Future { +internal class PutRepositoryBoxBase: PutRepository { + func put(_: T?, in _: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } - func putAll(_ array: [T], in query: Query, operation: Operation) -> Future<[T]> { + func putAll(_: [T], in _: Query, operation _: Operation) -> Future<[T]> { fatalError("This method is abstract.") } } /// -/// A repository box, which has as generic type a PutRepository and links the PutRepositoryBoxBase type T as the Base.T type. +/// A repository box, which has as generic type a PutRepository and links the PutRepositoryBoxBase type T as the +// Base.T type. /// -internal class PutRepositoryBox : PutRepositoryBoxBase { - +internal class PutRepositoryBox: PutRepositoryBoxBase { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/Repository/AnyRepository.swift b/Sources/Harmony/Data/Repository/AnyRepository.swift index 96b47646..328b34ef 100644 --- a/Sources/Harmony/Data/Repository/AnyRepository.swift +++ b/Sources/Harmony/Data/Repository/AnyRepository.swift @@ -19,8 +19,7 @@ import Foundation /// /// A type eraser for the Repository type, following Apple's Swift Standard Library approach. /// -public final class AnyRepository : GetRepository, PutRepository, DeleteRepository { - +public final class AnyRepository: GetRepository, PutRepository, DeleteRepository { private let box: RepositoryBoxBase /// Default initializer. @@ -58,40 +57,41 @@ public final class AnyRepository : GetRepository, PutRepository, DeleteRepos /// /// This is an abstract class. Do not use it. -/// Repository base class defining a generic type T (which is unrelated to the associated type of the Repository protocol) +/// Repository base class defining a generic type T (which is unrelated to the associated type of the Repository +// protocol) /// -internal class RepositoryBoxBase : GetRepository, PutRepository, DeleteRepository { - - func get(_ query: Query, operation: Operation) -> Future { +internal class RepositoryBoxBase: GetRepository, PutRepository, DeleteRepository { + func get(_: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } - func getAll(_ query: Query, operation: Operation) -> Future<[T]> { + func getAll(_: Query, operation _: Operation) -> Future<[T]> { fatalError("This method is abstract.") } - func put(_ value: T?, in query: Query, operation: Operation) -> Future { + func put(_: T?, in _: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } - func putAll(_ array: [T], in query: Query, operation: Operation) -> Future<[T]> { + func putAll(_: [T], in _: Query, operation _: Operation) -> Future<[T]> { fatalError("This method is abstract.") } - func delete(_ query: Query, operation: Operation) -> Future { + func delete(_: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } - func deleteAll(_ query: Query, operation: Operation) -> Future { + func deleteAll(_: Query, operation _: Operation) -> Future { fatalError("This method is abstract.") } } /// -/// A repository box, which has as generic type a Repository and links the RepositoryBoxBase type T as the Base.T type. +/// A repository box, which has as generic type a Repository and links the RepositoryBoxBase type T as the Base.T +// type. /// -internal class RepositoryBox : RepositoryBoxBase where Base: GetRepository, Base: PutRepository, Base: DeleteRepository { - +internal class RepositoryBox: RepositoryBoxBase where Base: GetRepository, Base: PutRepository, + Base: DeleteRepository { private let base: Base init(_ base: Base) { diff --git a/Sources/Harmony/Data/Repository/CacheRepository.swift b/Sources/Harmony/Data/Repository/CacheRepository.swift index 0897d34a..92955f84 100644 --- a/Sources/Harmony/Data/Repository/CacheRepository.swift +++ b/Sources/Harmony/Data/Repository/CacheRepository.swift @@ -17,10 +17,11 @@ import Foundation /// MainOperation: Data processing will only use the "main data source". -public class MainOperation: Operation { public init () { } } +public class MainOperation: Operation { public init() {} } -/// MainSyncOperation: Data processing will use the "main data source" and then sync result with the "cache data source". -public class MainSyncOperation: Operation { public init () { } } +/// MainSyncOperation: Data processing will use the "main data source" and then sync result with the "cache data +// source". +public class MainSyncOperation: Operation { public init() {} } /// CacheOperation: Data processing will only use the "cache data source". public class CacheOperation: Operation { @@ -47,6 +48,7 @@ public class CacheSyncOperation: Operation { public init(fallback: @escaping (Error) -> Bool = { _ in false }) { self.fallback = fallback } + /// Convenience initializer /// /// - Parameter fallback: The fallback behavior. @@ -58,14 +60,17 @@ public class CacheSyncOperation: Operation { /// /// Repository containing two data sources: a fast-access data source and a slow-access data source. /// -/// Using the `MainOperation`, `MainSyncOperation`, `CacheOperation` and `CacheSyncOperation`, the end user can access the fast or slow data source. -/// A typical example of usage is using this repository to alternate between a network-based data source (main data source) and a local cache storage data source (cache data source). +/// Using the `MainOperation`, `MainSyncOperation`, `CacheOperation` and `CacheSyncOperation`, the end user can +// access the fast or slow data source. +/// A typical example of usage is using this repository to alternate between a network-based data source (main data +// source) and a local cache storage data source (cache data source). /// -/// Note that by using the `DefaultOperation`, the CacheRepository will act as a regular cache: behaving as a `CacheSyncOperation` on GET methods and behaving as a `MainSyncOperation` on PUT and DELETE methods. +/// Note that by using the `DefaultOperation`, the CacheRepository will act as a regular cache: behaving as a +// `CacheSyncOperation` on GET methods and behaving as a `MainSyncOperation` on PUT and DELETE methods. /// public class CacheRepository: GetRepository, PutRepository, DeleteRepository -where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, C: PutDataSource, C: DeleteDataSource, M.T == T, C.T == T { - + where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, C: PutDataSource, + C: DeleteDataSource, M.T == T, C.T == T { private let main: M private let cache: C private let validator: ObjectValidation @@ -100,7 +105,7 @@ where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, } case is MainSyncOperation: return main.get(query).flatMap { entity in - return self.cache.put(entity, in: query) + self.cache.put(entity, in: query) } case let op as CacheSyncOperation: var cachedValue: T! @@ -154,7 +159,7 @@ where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, } case is MainSyncOperation: return main.getAll(query).flatMap { entities in - return self.cache.putAll(entities, in: query) + self.cache.putAll(entities, in: query) } case let op as CacheSyncOperation: var cachedValues: [T]! @@ -201,11 +206,11 @@ where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, return cache.put(value, in: query) case is MainSyncOperation: return main.put(value, in: query).flatMap { value in - return self.cache.put(value, in: query) + self.cache.put(value, in: query) } case is CacheSyncOperation: return cache.put(value, in: query).flatMap { value in - return self.main.put(value, in: query) + self.main.put(value, in: query) } default: operation.fatalError(.put, self) @@ -223,11 +228,11 @@ where M: GetDataSource, M: PutDataSource, M: DeleteDataSource, C: GetDataSource, return cache.putAll(array, in: query) case is MainSyncOperation: return main.putAll(array, in: query).flatMap { array in - return self.cache.putAll(array, in: query) + self.cache.putAll(array, in: query) } case is CacheSyncOperation: return cache.putAll(array, in: query).flatMap { array in - return self.main.putAll(array, in: query) + self.main.putAll(array, in: query) } default: operation.fatalError(.putAll, self) diff --git a/Sources/Harmony/Data/Repository/Repository.swift b/Sources/Harmony/Data/Repository/Repository.swift index 6be5411f..00a15091 100644 --- a/Sources/Harmony/Data/Repository/Repository.swift +++ b/Sources/Harmony/Data/Repository/Repository.swift @@ -16,10 +16,9 @@ import Foundation -public protocol Repository { } +public protocol Repository {} public protocol GetRepository: Repository { - associatedtype T /// Get a single method @@ -35,49 +34,49 @@ public protocol GetRepository: Repository { func getAll(_ query: Query, operation: Operation) -> Future<[T]> } -extension GetRepository { - public func get(_ id: K, operation: Operation) -> Future where K: Hashable { +public extension GetRepository { + func get(_ id: K, operation: Operation) -> Future where K: Hashable { return get(IdQuery(id), operation: operation) } - public func getAll(_ id: K, operation: Operation) -> Future<[T]> where K: Hashable { + func getAll(_ id: K, operation: Operation) -> Future<[T]> where K: Hashable { return getAll(IdQuery(id), operation: operation) } } public protocol PutRepository: Repository { - associatedtype T /// Put by query method /// /// - Parameter query: An instance conforming to Query that encapsules the get query information - /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. id or timestamp fields. + /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. + // id or timestamp fields. @discardableResult func put(_ value: T?, in query: Query, operation: Operation) -> Future /// Put by query method /// /// - Parameter query: An instance conforming to Query that encapsules the get query information - /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. id or timestamp fields. + /// - Returns: A future of T type. Some data sources might add some extra fields after the put operation, e.g. + // id or timestamp fields. @discardableResult func putAll(_ array: [T], in query: Query, operation: Operation) -> Future<[T]> } -extension PutRepository { +public extension PutRepository { @discardableResult - public func put(_ value: T?, forId id: K, operation: Operation) -> Future where K: Hashable { + func put(_ value: T?, forId id: K, operation: Operation) -> Future where K: Hashable { return put(value, in: IdQuery(id), operation: operation) } @discardableResult - public func putAll(_ array: [T], forId id: K, operation: Operation) -> Future<[T]> where K: Hashable { + func putAll(_ array: [T], forId id: K, operation: Operation) -> Future<[T]> where K: Hashable { return putAll(array, in: IdQuery(id), operation: operation) } } public protocol DeleteRepository: Repository { - /// Delete by query method /// /// - Parameter query: An instance conforming to Query that encapusles the delete query information @@ -89,20 +88,21 @@ public protocol DeleteRepository: Repository { /// /// - Parameter query: An instance conforming to Query that encapusles the delete query information /// - Returns: A future of Void type. - @available(*, deprecated, message: "Use delete with AllObjectsQuery to remove all entries or with any other Query to remove one or more entries") + @available(*, deprecated, + message: "Use delete with AllObjectsQuery to remove all entries or with any other Query to remove one or more entries") @discardableResult func deleteAll(_ query: Query, operation: Operation) -> Future } -extension DeleteRepository { +public extension DeleteRepository { @discardableResult - public func delete(_ id: K, operation: Operation) -> Future where K: Hashable { + func delete(_ id: K, operation: Operation) -> Future where K: Hashable { return delete(IdQuery(id), operation: operation) } @available(*, deprecated, message: "Use delete instead") @discardableResult - public func deleteAll(_ id: K, operation: Operation) -> Future where K: Hashable { + func deleteAll(_ id: K, operation: Operation) -> Future where K: Hashable { return deleteAll(IdQuery(id), operation: operation) } } @@ -127,8 +127,11 @@ public enum RepositoryCRUD: CustomStringConvertible { } } -extension Operation { - public func fatalError(_ method: RepositoryCRUD, _ origin: R) -> Never where R: Repository { - Swift.fatalError("Undefined operation \(String(describing: self)) for method \(method) on \(String(describing: type(of: origin)))") +public extension Operation { + func fatalError(_ method: RepositoryCRUD, _ origin: R) -> Never where R: Repository { + Swift + .fatalError( + "Undefined operation \(String(describing: self)) for method \(method) on \(String(describing: type(of: origin)))" + ) } } diff --git a/Sources/Harmony/Data/Repository/RepositoryAssembler.swift b/Sources/Harmony/Data/Repository/RepositoryAssembler.swift index 074f6760..bc5f156b 100644 --- a/Sources/Harmony/Data/Repository/RepositoryAssembler.swift +++ b/Sources/Harmony/Data/Repository/RepositoryAssembler.swift @@ -19,9 +19,13 @@ import Foundation /// /// Assambles a CRUD repository into a single repository object /// -public final class RepositoryAssembler : GetRepository, PutRepository, DeleteRepository -where Get.T == T, Put.T == T { - +public final class RepositoryAssembler< + Get: GetRepository, + Put: PutRepository, + Delete: DeleteRepository, + T +>: GetRepository, PutRepository, DeleteRepository + where Get.T == T, Put.T == T { private let getRepository: Get private let putRepository: Put private let deleteRepository: Delete @@ -67,68 +71,68 @@ where Get.T == T, Put.T == T { } } -extension RepositoryAssembler where Get == Put, Get == Delete { +public extension RepositoryAssembler where Get == Put, Get == Delete { /// Initializer for a single Repository /// /// - Parameter repository: The repository - public convenience init(_ repository: Get) { + convenience init(_ repository: Get) { self.init(get: repository, put: repository, delete: repository) } } -extension RepositoryAssembler where Put == VoidPutRepository, Delete == VoidDeleteRepository { +public extension RepositoryAssembler where Put == VoidPutRepository, Delete == VoidDeleteRepository { /// Initializer for a single Repository /// /// - Parameter getRepository: The repository - public convenience init(get getRepository: Get) { + convenience init(get getRepository: Get) { self.init(get: getRepository, put: VoidPutRepository(), delete: VoidDeleteRepository()) } } -extension RepositoryAssembler where Get == VoidGetRepository, Delete == VoidDeleteRepository { +public extension RepositoryAssembler where Get == VoidGetRepository, Delete == VoidDeleteRepository { /// Initializer for a single Repository /// /// - Parameter putRepository: The repository - public convenience init(put putRepository: Put) { + convenience init(put putRepository: Put) { self.init(get: VoidGetRepository(), put: putRepository, delete: VoidDeleteRepository()) } } -extension RepositoryAssembler where Get == VoidGetRepository, Put == VoidPutRepository { +public extension RepositoryAssembler where Get == VoidGetRepository, Put == VoidPutRepository { /// Initializer for a single Repository /// /// - Parameter deleteRepository: The repository - public convenience init(delete deleteRepository: Delete) { + convenience init(delete deleteRepository: Delete) { self.init(get: VoidGetRepository(), put: VoidPutRepository(), delete: deleteRepository) } } -extension RepositoryAssembler where Get == VoidGetRepository { +public extension RepositoryAssembler where Get == VoidGetRepository { /// Initializer for a single Repository /// /// - Parameter putRepository: The repository /// - Parameter deleteRepository: The repository - public convenience init(put putRepository: Put, delete deleteRepository: Delete) { + convenience init(put putRepository: Put, delete deleteRepository: Delete) { self.init(get: VoidGetRepository(), put: putRepository, delete: deleteRepository) } } -extension RepositoryAssembler where Put == VoidPutRepository { +public extension RepositoryAssembler where Put == VoidPutRepository { /// Initializer for a single Repository /// /// - Parameter getRepository: The repository /// - Parameter deleteRepository: The repository - public convenience init(get getRepository: Get, delete deleteRepository: Delete) { + convenience init(get getRepository: Get, delete deleteRepository: Delete) { self.init(get: getRepository, put: VoidPutRepository(), delete: deleteRepository) } } -extension RepositoryAssembler where Delete == VoidDeleteRepository { +public extension RepositoryAssembler where Delete == VoidDeleteRepository { /// Initializer for a single Repository /// /// - Parameter getRepository: The repository /// - Parameter putRepository: The repository - public convenience init(get getRepository: Get, put putRepository: Put) { + convenience init(get getRepository: Get, put putRepository: Put) { self.init(get: getRepository, put: putRepository, delete: VoidDeleteRepository()) } } diff --git a/Sources/Harmony/Data/Repository/RepositoryMapper.swift b/Sources/Harmony/Data/Repository/RepositoryMapper.swift index ea034847..0860c7ba 100644 --- a/Sources/Harmony/Data/Repository/RepositoryMapper.swift +++ b/Sources/Harmony/Data/Repository/RepositoryMapper.swift @@ -17,10 +17,10 @@ import Foundation /// -/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple "translator". +/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple +// "translator". /// -public class GetRepositoryMapper : GetRepository where R.T == In { - +public class GetRepositoryMapper: GetRepository where R.T == In { public typealias T = Out private let repository: R @@ -39,7 +39,7 @@ public class GetRepositoryMapper : GetRepository whe public func get(_ query: Query, operation: Operation) -> Future { return repository.get(query, operation: operation).map { value in - return try self.toOutMapper.map(value) + try self.toOutMapper.map(value) } } @@ -55,10 +55,10 @@ extension GetRepository { } /// -/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple "translator". +/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple +// "translator". /// -public class PutRepositoryMapper : PutRepository where R.T == In { - +public class PutRepositoryMapper: PutRepository where R.T == In { public typealias T = Out private let repository: R @@ -93,23 +93,25 @@ public class PutRepositoryMapper : PutRepository whe @discardableResult public func putAll(_ array: [Out], in query: Query, operation: Operation) -> Future<[Out]> { return Future { - return repository.putAll(try toInMapper.map(array), in: query, operation: operation).map { try self.toOutMapper.map($0) } + return repository.putAll(try toInMapper.map(array), in: query, operation: operation) + .map { try self.toOutMapper.map($0) } } } } extension PutRepository { - func withMapping(in toInMapper: Mapper, out toOutMapper: Mapper) -> PutRepositoryMapper { + func withMapping(in toInMapper: Mapper, + out toOutMapper: Mapper) -> PutRepositoryMapper { return PutRepositoryMapper(repository: self, toInMapper: toInMapper, toOutMapper: toOutMapper) } } /// -/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple "translator". +/// This repository uses mappers to map objects and redirects them to the contained repository, acting as a simple +// "translator". /// -public class RepositoryMapper : GetRepository, PutRepository, DeleteRepository -where R: GetRepository, R: PutRepository, R: DeleteRepository, R.T == In { - +public class RepositoryMapper: GetRepository, PutRepository, DeleteRepository + where R: GetRepository, R: PutRepository, R: DeleteRepository, R.T == In { public typealias T = Out private let repository: R @@ -132,7 +134,7 @@ where R: GetRepository, R: PutRepository, R: DeleteRepository, R.T == In { public func get(_ query: Query, operation: Operation) -> Future { return repository.get(query, operation: operation).map { value in - return try self.toOutMapper.map(value) + try self.toOutMapper.map(value) } } @@ -154,7 +156,8 @@ where R: GetRepository, R: PutRepository, R: DeleteRepository, R.T == In { @discardableResult public func putAll(_ array: [Out], in query: Query, operation: Operation) -> Future<[Out]> { return Future { - return repository.putAll(try toInMapper.map(array), in: query, operation: operation).map { try self.toOutMapper.map($0) } + return repository.putAll(try toInMapper.map(array), in: query, operation: operation) + .map { try self.toOutMapper.map($0) } } } diff --git a/Sources/Harmony/Data/Repository/RetryRepository.swift b/Sources/Harmony/Data/Repository/RetryRepository.swift index 58941b3e..fb1f5309 100644 --- a/Sources/Harmony/Data/Repository/RetryRepository.swift +++ b/Sources/Harmony/Data/Repository/RetryRepository.swift @@ -35,7 +35,7 @@ private struct RetryRule { /// /// - Returns: The next retry rule public func next() -> RetryRule { - return RetryRule(count: count-1, retryIf: retryIf) + return RetryRule(count: count - 1, retryIf: retryIf) } } @@ -43,7 +43,6 @@ private struct RetryRule { /// The retry operation /// public class RetryOperation: Operation { - /// The retry rule private let retryRule: RetryRule @@ -55,10 +54,11 @@ public class RetryOperation: Operation { /// - Parameters_ /// - operation: The operation that will be forwarded to the nested repository /// - count: The retry counter. Default value is 1. - /// - retryIf: A closure to evaluate each retry error. Return true to allow a retry, false otherwise. Default closure returns true. + /// - retryIf: A closure to evaluate each retry error. Return true to allow a retry, false otherwise. Default + // closure returns true. public init(_ operation: Operation, count: Int = 1, retryIf: @escaping (Error) -> Bool = { _ in true }) { self.operation = operation - self.retryRule = RetryRule(count: count, retryIf: retryIf) + retryRule = RetryRule(count: count, retryIf: retryIf) } fileprivate init(_ operation: Operation, _ retryRule: RetryRule) { @@ -86,8 +86,8 @@ public class RetryOperation: Operation { /// Repository adding a retry logic over an existing repository when an error happens. /// Incoming operations of a different type as RetryOperation will be forwarded to the contained repository. /// -public class RetryRepository : GetRepository, PutRepository, DeleteRepository where R: GetRepository, R: PutRepository, R: DeleteRepository, T == R.T { - +public class RetryRepository: GetRepository, PutRepository, DeleteRepository where R: GetRepository, + R: PutRepository, R: DeleteRepository, T == R.T { /// The nested repository private let repository: R @@ -100,7 +100,7 @@ public class RetryRepository : GetRepository, PutRepository, DeleteReposi /// - repository: The contained repository public init(_ repository: R, retryCount: Int = 1, retryIf: @escaping (Error) -> Bool = { _ in true }) { self.repository = repository - self.retryRule = RetryRule(count: retryCount, retryIf: retryIf) + retryRule = RetryRule(count: retryCount, retryIf: retryIf) } public func get(_ query: Query, operation: Operation) -> Future { diff --git a/Sources/Harmony/Data/Repository/SingleDataSourceRepository.swift b/Sources/Harmony/Data/Repository/SingleDataSourceRepository.swift index cfe3f162..8d2ed3f9 100644 --- a/Sources/Harmony/Data/Repository/SingleDataSourceRepository.swift +++ b/Sources/Harmony/Data/Repository/SingleDataSourceRepository.swift @@ -22,7 +22,6 @@ import Foundation /// Operation parameter is not used in any case. /// public class SingleGetDataSourceRepository: GetRepository where D.T == T { - private let dataSource: D /// Default initializer @@ -33,20 +32,20 @@ public class SingleGetDataSourceRepository: GetRepository w self.dataSource = dataSource } - public func get(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func get(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.get(query) } - public func getAll(_ query: Query, operation: Operation = DefaultOperation()) -> Future<[T]> { + public func getAll(_ query: Query, operation _: Operation = DefaultOperation()) -> Future<[T]> { return dataSource.getAll(query) } } -extension GetDataSource { +public extension GetDataSource { /// Creates a single data source repository from a data source /// /// - Returns: A SingleGetDataSourceRepository repository - public func toGetRepository() -> SingleGetDataSourceRepository { + func toGetRepository() -> SingleGetDataSourceRepository { return SingleGetDataSourceRepository(self) } } @@ -57,7 +56,6 @@ extension GetDataSource { /// Operation parameter is not used in any case. /// public class SinglePutDataSourceRepository: PutRepository where D.T == T { - private let dataSource: D /// Default initializer @@ -69,21 +67,21 @@ public class SinglePutDataSourceRepository: PutRepository w } @discardableResult - public func put(_ value: T?, in query: Query, operation: Operation = DefaultOperation()) -> Future { + public func put(_ value: T?, in query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.put(value, in: query) } @discardableResult - public func putAll(_ array: [T], in query: Query, operation: Operation = DefaultOperation()) -> Future<[T]> { + public func putAll(_ array: [T], in query: Query, operation _: Operation = DefaultOperation()) -> Future<[T]> { return dataSource.putAll(array, in: query) } } -extension PutDataSource { +public extension PutDataSource { /// Creates a single data source repository from a data source /// /// - Returns: A SinglePutDataSourceRepository repository - public func toPutRepository() -> SinglePutDataSourceRepository { + func toPutRepository() -> SinglePutDataSourceRepository { return SinglePutDataSourceRepository(self) } } @@ -94,7 +92,6 @@ extension PutDataSource { /// Operation parameter is not used in any case. /// public class SingleDeleteDataSourceRepository: DeleteRepository { - private let dataSource: D /// Default initializer @@ -106,21 +103,21 @@ public class SingleDeleteDataSourceRepository: DeleteReposi } @discardableResult - public func delete(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func delete(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.delete(query) } @discardableResult - public func deleteAll(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func deleteAll(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.deleteAll(query) } } -extension DeleteDataSource { +public extension DeleteDataSource { /// Creates a single data source repository from a data source /// /// - Returns: A SingleDeleteDataSourceRepository repository - public func toDeleteRepository() -> SingleDeleteDataSourceRepository { + func toDeleteRepository() -> SingleDeleteDataSourceRepository { return SingleDeleteDataSourceRepository(self) } } @@ -131,8 +128,7 @@ extension DeleteDataSource { /// Operation parameter is not used in any case. /// public class SingleDataSourceRepository: GetRepository, PutRepository, DeleteRepository -where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - + where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { private let dataSource: D /// Main initializer @@ -143,31 +139,31 @@ where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { self.dataSource = dataSource } - public func get(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func get(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.get(query) } - public func getAll(_ query: Query, operation: Operation = DefaultOperation()) -> Future<[T]> { + public func getAll(_ query: Query, operation _: Operation = DefaultOperation()) -> Future<[T]> { return dataSource.getAll(query) } @discardableResult - public func put(_ value: T?, in query: Query, operation: Operation = DefaultOperation()) -> Future { + public func put(_ value: T?, in query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.put(value, in: query) } @discardableResult - public func putAll(_ array: [T], in query: Query, operation: Operation = DefaultOperation()) -> Future<[T]> { + public func putAll(_ array: [T], in query: Query, operation _: Operation = DefaultOperation()) -> Future<[T]> { return dataSource.putAll(array, in: query) } @discardableResult - public func delete(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func delete(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.delete(query) } @discardableResult - public func deleteAll(_ query: Query, operation: Operation = DefaultOperation()) -> Future { + public func deleteAll(_ query: Query, operation _: Operation = DefaultOperation()) -> Future { return dataSource.deleteAll(query) } } diff --git a/Sources/Harmony/Data/Repository/VoidRepository.swift b/Sources/Harmony/Data/Repository/VoidRepository.swift index 0a29f7ce..7c55bcb7 100644 --- a/Sources/Harmony/Data/Repository/VoidRepository.swift +++ b/Sources/Harmony/Data/Repository/VoidRepository.swift @@ -20,38 +20,48 @@ import Foundation /// Void get repository implementation /// public class VoidGetRepository: GetRepository { - public init() { } - public func get(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func getAll(_ query: Query, operation: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public init() {} + public func get(_: Query, operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func getAll(_: Query, + operation _: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } } /// /// Void put repository implementation /// public class VoidPutRepository: PutRepository { - public init() { } - public func put(_ value: T?, in query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func putAll(_ array: [T], in query: Query, operation: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public init() {} + public func put(_: T?, in _: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func putAll(_: [T], in _: Query, + operation _: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } } /// /// Void delete repository implementation /// public class VoidDeleteRepository: DeleteRepository { - public init() { } - public func delete(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func deleteAll(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public init() {} + public func delete(_: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func deleteAll(_: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } } /// /// Void repository implementation /// public class VoidRepository: GetRepository, PutRepository, DeleteRepository { - public init() { } - public func get(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func getAll(_ query: Query, operation: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } - public func put(_ value: T?, in query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func putAll(_ array: [T], in query: Query, operation: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } - public func delete(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } - public func deleteAll(_ query: Query, operation: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public init() {} + public func get(_: Query, operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func getAll(_: Query, + operation _: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public func put(_: T?, in _: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func putAll(_: [T], in _: Query, + operation _: Operation) -> Future<[T]> { return Future(CoreError.NotImplemented()) } + public func delete(_: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } + public func deleteAll(_: Query, + operation _: Operation) -> Future { return Future(CoreError.NotImplemented()) } } diff --git a/Sources/Harmony/Data/Validator/ObjectValidation.swift b/Sources/Harmony/Data/Validator/ObjectValidation.swift index 59eeb405..ca30a494 100644 --- a/Sources/Harmony/Data/Validator/ObjectValidation.swift +++ b/Sources/Harmony/Data/Validator/ObjectValidation.swift @@ -26,7 +26,6 @@ public protocol ObjectValidation { } public extension ObjectValidation { - /// Validator method for arrays /// /// The validation process iterates over the array and is considered valid if all objects are valid. @@ -54,7 +53,7 @@ public extension ObjectValidation { /// public class DefaultObjectValidation: ObjectValidation { public init() {} - public func isObjectValid(_ object: T) -> Bool { + public func isObjectValid(_: T) -> Bool { return true } } diff --git a/Sources/Harmony/Data/Validator/VastraReachabilityStrategy.swift b/Sources/Harmony/Data/Validator/VastraReachabilityStrategy.swift index 55dc473c..1163a4f6 100644 --- a/Sources/Harmony/Data/Validator/VastraReachabilityStrategy.swift +++ b/Sources/Harmony/Data/Validator/VastraReachabilityStrategy.swift @@ -35,7 +35,7 @@ public class VastraReachabilityStrategy: VastraStrategy { self.reachability = reachability } - public func isObjectValid(_ object: T) -> VastraStrategyResult { + public func isObjectValid(_: T) -> VastraStrategyResult { if reachability.isReachable() { return .unknown } else { diff --git a/Sources/Harmony/Data/Validator/VastraService.swift b/Sources/Harmony/Data/Validator/VastraService.swift index 292a1a46..506e39ca 100644 --- a/Sources/Harmony/Data/Validator/VastraService.swift +++ b/Sources/Harmony/Data/Validator/VastraService.swift @@ -21,9 +21,9 @@ import Foundation /// /// The first strategy that validates or invalidates the object will define the validity of the object. /// -/// If any strategy succeeds to validate or invalidate the object, the validation will fail and the object will be considered as invalid. +/// If any strategy succeeds to validate or invalidate the object, the validation will fail and the object will be +// considered as invalid. public class VastraService { - /// Array of validation strategies. public let strategies: [VastraStrategy] @@ -33,6 +33,7 @@ public class VastraService { public init(_ strategies: [VastraStrategy]) { self.strategies = strategies } + /// If none of the strategies can resolve the state, this is the object validation state returned public var defaultValidationState = false diff --git a/Sources/Harmony/Data/Validator/VastraStrategy.swift b/Sources/Harmony/Data/Validator/VastraStrategy.swift index 7d10fb14..d8d90f11 100644 --- a/Sources/Harmony/Data/Validator/VastraStrategy.swift +++ b/Sources/Harmony/Data/Validator/VastraStrategy.swift @@ -31,7 +31,6 @@ public enum VastraStrategyResult { /// Superclass strategy. Sublcasses will define custom strategies. /// public protocol VastraStrategy { - /// Strategy validation method. /// /// - Parameter object: The object to test diff --git a/Sources/Harmony/Data/Validator/VastraTimestampStrategy.swift b/Sources/Harmony/Data/Validator/VastraTimestampStrategy.swift index c5b7c7f5..6d24342c 100644 --- a/Sources/Harmony/Data/Validator/VastraTimestampStrategy.swift +++ b/Sources/Harmony/Data/Validator/VastraTimestampStrategy.swift @@ -35,7 +35,7 @@ public enum Time { case let .days(value): return Double(value * 86400) case let .weeks(value): - return Double(value * 604800) + return Double(value * 604_800) case .never: return nil } @@ -44,17 +44,18 @@ public enum Time { /// Objects that will be validated using the VastraTimestampStrategy must implement this protocol. public protocol VastraTimestampStrategyDataSource { - var lastUpdate: Date? {get} + var lastUpdate: Date? { get } func expiryTimeInterval() -> Time } /// The strategy will measure the elapsed timeinterval from the `lastUpdate` to the current time. /// /// - If the elapsed timeinterval is smaller than expiryTimeInterval: The object will be considered valid (.Valid) -/// - If the elapsed timeinterval is greater than or equal to expiryTimeInterval: The object will be considered invalid (.Invalid) +/// - If the elapsed timeinterval is greater than or equal to expiryTimeInterval: The object will be considered +// invalid (.Invalid) /// - If there is no a lastUpdate date, the strategy won't decide object validity (.Unknown) public class VastraTimestampStrategy: VastraStrategy { - public init() { } + public init() {} public func isObjectValid(_ object: T) -> VastraStrategyResult { let lastUpdate = (object as! VastraTimestampStrategyDataSource).lastUpdate @@ -65,7 +66,7 @@ public class VastraTimestampStrategy: VastraStrategy { let expiryTime = (object as! VastraTimestampStrategyDataSource).expiryTimeInterval() let diff = Date().timeIntervalSince(lastUpdate!) - guard let seconds = expiryTime.toSeconds() else { + guard let seconds = expiryTime.toSeconds() else { return .invalid } diff --git a/Sources/Harmony/Domain/Interactor/Interactor.swift b/Sources/Harmony/Domain/Interactor/Interactor.swift index 8b12e77c..f76a6abe 100644 --- a/Sources/Harmony/Domain/Interactor/Interactor.swift +++ b/Sources/Harmony/Domain/Interactor/Interactor.swift @@ -17,4 +17,4 @@ import Foundation // Namespace definition -public struct Interactor { } +public struct Interactor {} diff --git a/Sources/Harmony/Domain/Interactor/InteractorDelete.swift b/Sources/Harmony/Domain/Interactor/InteractorDelete.swift index 6d8ccbcd..90c236d7 100644 --- a/Sources/Harmony/Domain/Interactor/InteractorDelete.swift +++ b/Sources/Harmony/Domain/Interactor/InteractorDelete.swift @@ -21,7 +21,6 @@ extension Interactor { /// Generic delete object by query interactor /// open class DeleteByQuery { - private let executor: Executor private let repository: DeleteRepository @@ -31,7 +30,8 @@ extension Interactor { } @discardableResult - open func execute(_ query: Query, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute(_ query: Query, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.delete(query, operation: operation)) @@ -39,7 +39,8 @@ extension Interactor { } @discardableResult - open func execute(_ id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { + open func execute(_ id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.delete(id, operation: operation)) @@ -51,7 +52,6 @@ extension Interactor { /// Generic delete object interactor /// open class Delete { - private let query: Query private let executor: Executor private let repository: DeleteRepository @@ -62,12 +62,14 @@ extension Interactor { self.repository = repository } - public convenience init(_ executor: Executor, _ repository: DeleteRepository, _ id: K) where K: Hashable { + public convenience init(_ executor: Executor, _ repository: DeleteRepository, _ id: K) + where K: Hashable { self.init(executor, repository, IdQuery(id)) } @discardableResult - open func execute(_ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute(_ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.delete(self.query, operation: operation)) @@ -79,7 +81,6 @@ extension Interactor { /// Generic delete objects interactor /// open class DeleteAllByQuery { - private let executor: Executor private let repository: DeleteRepository @@ -89,7 +90,8 @@ extension Interactor { } @discardableResult - open func execute(_ query: Query, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute(_ query: Query, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.deleteAll(query, operation: operation)) @@ -97,7 +99,8 @@ extension Interactor { } @discardableResult - open func execute(_ id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { + open func execute(_ id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.deleteAll(id, operation: operation)) @@ -109,7 +112,6 @@ extension Interactor { /// Generic delete objects interactor /// open class DeleteAll { - private let query: Query private let executor: Executor private let repository: DeleteRepository @@ -120,12 +122,14 @@ extension Interactor { self.repository = repository } - public convenience init(_ executor: Executor, _ repository: DeleteRepository, _ id: K) where K: Hashable { + public convenience init(_ executor: Executor, _ repository: DeleteRepository, _ id: K) + where K: Hashable { self.init(executor, repository, IdQuery(id)) } @discardableResult - open func execute(_ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute(_ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.deleteAll(self.query, operation: operation)) @@ -134,28 +138,28 @@ extension Interactor { } } -extension DeleteRepository { - public func toDeleteByQueryInteractor(_ executor: Executor) -> Interactor.DeleteByQuery { +public extension DeleteRepository { + func toDeleteByQueryInteractor(_ executor: Executor) -> Interactor.DeleteByQuery { return Interactor.DeleteByQuery(executor, self) } - public func toDeleteInteractor(_ executor: Executor, _ query: Query) -> Interactor.Delete { + func toDeleteInteractor(_ executor: Executor, _ query: Query) -> Interactor.Delete { return Interactor.Delete(executor, self, query) } - public func toDeleteInteractor(_ executor: Executor, _ id: K) -> Interactor.Delete where K: Hashable { + func toDeleteInteractor(_ executor: Executor, _ id: K) -> Interactor.Delete where K: Hashable { return Interactor.Delete(executor, self, id) } - public func toDeleteAllByQueryInteractor(_ executor: Executor) -> Interactor.DeleteAllByQuery { + func toDeleteAllByQueryInteractor(_ executor: Executor) -> Interactor.DeleteAllByQuery { return Interactor.DeleteAllByQuery(executor, self) } - public func toDeleteAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.DeleteAll { + func toDeleteAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.DeleteAll { return Interactor.DeleteAll(executor, self, query) } - public func toDeleteAllInteractor(_ executor: Executor, _ id: K) -> Interactor.DeleteAll where K: Hashable { + func toDeleteAllInteractor(_ executor: Executor, _ id: K) -> Interactor.DeleteAll where K: Hashable { return Interactor.DeleteAll(executor, self, id) } } diff --git a/Sources/Harmony/Domain/Interactor/InteractorGet.swift b/Sources/Harmony/Domain/Interactor/InteractorGet.swift index b425b476..fe31a71a 100644 --- a/Sources/Harmony/Domain/Interactor/InteractorGet.swift +++ b/Sources/Harmony/Domain/Interactor/InteractorGet.swift @@ -23,7 +23,6 @@ extension Interactor { /// Generic get object interactor /// open class GetByQuery { - private let executor: Executor private let repository: AnyGetRepository @@ -32,14 +31,19 @@ extension Interactor { self.repository = repository.asAnyGetRepository() } - open func execute(_ query: Query = VoidQuery(), _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute( + _ query: Query = VoidQuery(), + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.get(query, operation: operation)) } } - open func execute(_ id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { + open func execute(_ id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.get(id, operation: operation)) @@ -51,18 +55,19 @@ extension Interactor { /// Generic get object interactor with a prefilled query /// open class Get { - private let query: Query private let executor: Executor private let repository: AnyGetRepository - public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: GetRepository, R.T == T { + public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: GetRepository, + R.T == T { self.query = query self.executor = executor self.repository = repository.asAnyGetRepository() } - public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, R: GetRepository, R.T == T { + public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, + R: GetRepository, R.T == T { self.init(executor, repository, IdQuery(id)) } @@ -78,7 +83,6 @@ extension Interactor { /// Generic get objects interactor /// open class GetAllByQuery { - private let executor: Executor private let repository: AnyGetRepository @@ -87,14 +91,19 @@ extension Interactor { self.repository = repository.asAnyGetRepository() } - open func execute(_ query: Query = AllObjectsQuery(), _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { + open func execute( + _ query: Query = AllObjectsQuery(), + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future<[T]> { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.getAll(query, operation: operation)) } } - open func execute(_ id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> where K: Hashable { + open func execute(_ id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future<[T]> where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.getAll(id, operation: operation)) @@ -106,22 +115,24 @@ extension Interactor { /// Generic get all objects interactor /// open class GetAll { - private let query: Query private let executor: Executor private let repository: AnyGetRepository - public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: GetRepository, R.T == T { + public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: GetRepository, + R.T == T { self.query = query self.executor = executor self.repository = repository.asAnyGetRepository() } - public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, R: GetRepository, R.T == T { + public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, + R: GetRepository, R.T == T { self.init(executor, repository, IdQuery(id)) } - open func execute(_ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { + open func execute(_ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future<[T]> { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.getAll(self.query, operation: operation)) @@ -130,28 +141,28 @@ extension Interactor { } } -extension GetRepository { - public func toGetByQueryInteractor(_ executor: Executor) -> Interactor.GetByQuery { +public extension GetRepository { + func toGetByQueryInteractor(_ executor: Executor) -> Interactor.GetByQuery { return Interactor.GetByQuery(executor, self) } - public func toGetInteractor(_ executor: Executor, _ query: Query) -> Interactor.Get { + func toGetInteractor(_ executor: Executor, _ query: Query) -> Interactor.Get { return Interactor.Get(executor, self, query) } - public func toGetInteractor(_ executor: Executor, _ id: K) -> Interactor.Get where K: Hashable { + func toGetInteractor(_ executor: Executor, _ id: K) -> Interactor.Get where K: Hashable { return Interactor.Get(executor, self, id) } - public func toGetAllByQueryInteractor(_ executor: Executor) -> Interactor.GetAllByQuery { + func toGetAllByQueryInteractor(_ executor: Executor) -> Interactor.GetAllByQuery { return Interactor.GetAllByQuery(executor, self) } - public func toGetAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.GetAll { + func toGetAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.GetAll { return Interactor.GetAll(executor, self, query) } - public func toGetAllInteractor(_ executor: Executor, _ id: K) -> Interactor.GetAll where K: Hashable { + func toGetAllInteractor(_ executor: Executor, _ id: K) -> Interactor.GetAll where K: Hashable { return Interactor.GetAll(executor, self, id) } } diff --git a/Sources/Harmony/Domain/Interactor/InteractorPut.swift b/Sources/Harmony/Domain/Interactor/InteractorPut.swift index 117beb8c..6cf7f78e 100644 --- a/Sources/Harmony/Domain/Interactor/InteractorPut.swift +++ b/Sources/Harmony/Domain/Interactor/InteractorPut.swift @@ -23,7 +23,6 @@ extension Interactor { /// Generic put object by query interactor /// open class PutByQuery { - private let executor: Executor private let repository: AnyPutRepository @@ -33,7 +32,12 @@ extension Interactor { } @discardableResult - open func execute(_ value: T? = nil, query: Query = VoidQuery(), _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute( + _ value: T? = nil, + query: Query = VoidQuery(), + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.put(value, in: query, operation: operation)) @@ -41,7 +45,8 @@ extension Interactor { } @discardableResult - open func execute(_ value: T?, forId id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { + open func execute(_ value: T?, forId id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.put(value, forId: id, operation: operation)) @@ -53,23 +58,28 @@ extension Interactor { /// Generic put object interactor /// open class Put { - private let query: Query private let executor: Executor private let repository: AnyPutRepository - public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: PutRepository, R.T == T { + public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: PutRepository, + R.T == T { self.query = query self.executor = executor self.repository = repository.asAnyPutRepository() } - public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, R: PutRepository, R.T == T { + public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, + R: PutRepository, R.T == T { self.init(executor, repository, IdQuery(id)) } @discardableResult - open func execute(_ value: T? = nil, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { + open func execute( + _ value: T? = nil, + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.put(value, in: self.query, operation: operation)) @@ -81,7 +91,6 @@ extension Interactor { /// Generic put objects by query interactor /// open class PutAllByQuery { - private let executor: Executor private let repository: AnyPutRepository @@ -91,7 +100,12 @@ extension Interactor { } @discardableResult - open func execute(_ array: [T] = [], query: Query = VoidQuery(), _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { + open func execute( + _ array: [T] = [], + query: Query = VoidQuery(), + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future<[T]> { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.putAll(array, in: query, operation: operation)) @@ -99,7 +113,8 @@ extension Interactor { } @discardableResult - open func execute(_ array: [T] = [], forId id: K, _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> where K: Hashable { + open func execute(_ array: [T] = [], forId id: K, _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil) -> Future<[T]> where K: Hashable { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.putAll(array, forId: id, operation: operation)) @@ -111,23 +126,28 @@ extension Interactor { /// Generic put objects interactor /// open class PutAll { - private let query: Query private let executor: Executor private let repository: AnyPutRepository - public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: PutRepository, R.T == T { + public required init(_ executor: Executor, _ repository: R, _ query: Query) where R: PutRepository, + R.T == T { self.query = query self.executor = executor self.repository = repository.asAnyPutRepository() } - public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, R: PutRepository, R.T == T { + public convenience init(_ executor: Executor, _ repository: R, _ id: K) where K: Hashable, + R: PutRepository, R.T == T { self.init(executor, repository, IdQuery(id)) } @discardableResult - open func execute(_ array: [T] = [], _ operation: Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { + open func execute( + _ array: [T] = [], + _ operation: Operation = DefaultOperation(), + in executor: Executor? = nil + ) -> Future<[T]> { let executor = executor ?? self.executor return executor.submit { resolver in resolver.set(self.repository.putAll(array, in: self.query, operation: operation)) @@ -136,28 +156,28 @@ extension Interactor { } } -extension PutRepository { - public func toPutByQueryInteractor(_ executor: Executor) -> Interactor.PutByQuery { +public extension PutRepository { + func toPutByQueryInteractor(_ executor: Executor) -> Interactor.PutByQuery { return Interactor.PutByQuery(executor, self) } - public func toPutInteractor(_ executor: Executor, _ query: Query) -> Interactor.Put { + func toPutInteractor(_ executor: Executor, _ query: Query) -> Interactor.Put { return Interactor.Put(executor, self, query) } - public func toPutInteractor(_ executor: Executor, _ id: K) -> Interactor.Put where K: Hashable { + func toPutInteractor(_ executor: Executor, _ id: K) -> Interactor.Put where K: Hashable { return Interactor.Put(executor, self, id) } - public func toPutAllByQueryInteractor(_ executor: Executor) -> Interactor.PutAllByQuery { + func toPutAllByQueryInteractor(_ executor: Executor) -> Interactor.PutAllByQuery { return Interactor.PutAllByQuery(executor, self) } - public func toPutAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.PutAll { + func toPutAllInteractor(_ executor: Executor, _ query: Query) -> Interactor.PutAll { return Interactor.PutAll(executor, self, query) } - public func toPutAllInteractor(_ executor: Executor, _ id: K) -> Interactor.PutAll where K: Hashable { + func toPutAllInteractor(_ executor: Executor, _ id: K) -> Interactor.PutAll where K: Hashable { return Interactor.PutAll(executor, self, id) } } diff --git a/Sources/Harmony/Future/Executor/Collections+Executor.swift b/Sources/Harmony/Future/Executor/Collections+Executor.swift index f7d521db..beb23565 100644 --- a/Sources/Harmony/Future/Executor/Collections+Executor.swift +++ b/Sources/Harmony/Future/Executor/Collections+Executor.swift @@ -16,8 +16,7 @@ import Foundation -extension Array { - +public extension Array { /// Executor-based map method /// /// - Parameters: @@ -25,8 +24,8 @@ extension Array { /// - transform: The mapping closure /// - Returns: An array of mapped elements /// - Throws: The first mapping thrown error - public func map(_ executor: Executor, _ transform : @escaping (Element) throws -> T) rethrows -> [T] { - let futures: [Future] = self.map { element in + func map(_ executor: Executor, _ transform: @escaping (Element) throws -> T) rethrows -> [T] { + let futures: [Future] = map { element in let future: Future = executor.submit { resolver in resolver.set(try transform(element)) } @@ -36,8 +35,7 @@ extension Array { } } -extension Set { - +public extension Set { /// Executor-based map method /// /// - Parameters: @@ -45,8 +43,8 @@ extension Set { /// - transform: The mapping closure /// - Returns: A set of mapped elements /// - Throws: The first mapping thrown error - public func map(_ executor: Executor, _ transform : @escaping (Element) throws -> T) rethrows -> [T] { - let futures: [Future] = self.map { element in + func map(_ executor: Executor, _ transform: @escaping (Element) throws -> T) rethrows -> [T] { + let futures: [Future] = map { element in let future: Future = executor.submit { resolver in resolver.set(try transform(element)) } @@ -56,8 +54,7 @@ extension Set { } } -extension Dictionary { - +public extension Dictionary { /// Executor-based map method /// /// - Parameters: @@ -65,8 +62,9 @@ extension Dictionary { /// - transform: The mapping closure /// - Returns: A dictionary with mapped keys /// - Throws: The first mapping thrown error - public func mapKeys(_ executor: Executor, _ transform : @escaping (Key) throws -> T) rethrows -> [T: Value] { - let futures: [Future<(T, Value)>] = self.map { (key, value) in + func mapKeys(_ executor: Executor, + _ transform: @escaping (Key) throws -> T) rethrows -> [T: Value] { + let futures: [Future<(T, Value)>] = map { key, value in let future: Future<(T, Value)> = executor.submit { resolver in resolver.set((try transform(key), value)) } @@ -88,9 +86,9 @@ extension Dictionary { /// - transform: The mapping closure /// - Returns: A dictionary with mapped values /// - Throws: The first mapping thrown error - public func mapValues(_ executor: Executor, _ transform : @escaping (Value) throws -> T) rethrows -> [Key: T] { + func mapValues(_ executor: Executor, _ transform: @escaping (Value) throws -> T) rethrows -> [Key: T] { return try map(executor) { element -> T in - return try transform(element.value) + try transform(element.value) } } @@ -101,8 +99,9 @@ extension Dictionary { /// - transform: The mapping closure /// - Returns: A dictionary with mapped values /// - Throws: The first mapping thrown error - public func map(_ executor: Executor, _ transform : @escaping ((key: Key, value: Value)) throws -> T) rethrows -> [Key: T] { - let futures: [Future<(Key, T)>] = self.map { (key, value) in + func map(_ executor: Executor, + _ transform: @escaping ((key: Key, value: Value)) throws -> T) rethrows -> [Key: T] { + let futures: [Future<(Key, T)>] = map { key, value in let future: Future<(Key, T)> = executor.submit { resolver in resolver.set((key, try transform((key, value)))) } diff --git a/Sources/Harmony/Future/Executor/DirectExecutor.swift b/Sources/Harmony/Future/Executor/DirectExecutor.swift index f7b81dc4..9e2784e3 100644 --- a/Sources/Harmony/Future/Executor/DirectExecutor.swift +++ b/Sources/Harmony/Future/Executor/DirectExecutor.swift @@ -23,7 +23,7 @@ public class DirectExecutor: Executor { public private(set) var executing: Bool = false public let name: String? = "com.mobilejazz.executor.direct" - public init() { } + public init() {} public func submit(_ closure: @escaping (@escaping () -> Void) -> Void) { executing = true @@ -35,7 +35,6 @@ public class DirectExecutor: Executor { } public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor { - private let overrideDelay: Bool public init(overrideDelay: Bool = false) { @@ -43,8 +42,8 @@ public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor } public func submit(after: DispatchTime, _ closure: @escaping (@escaping () -> Void) -> Void) { - if self.overrideDelay { - self.submit(closure) + if overrideDelay { + submit(closure) } else { DispatchQueue.main.asyncAfter(deadline: after) { self.executing = true @@ -56,9 +55,12 @@ public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor } } - @discardableResult public func submit(after: DispatchTime, _ closure: @escaping (FutureResolver) throws -> Void) -> Future { + @discardableResult public func submit( + after: DispatchTime, + _ closure: @escaping (FutureResolver) throws -> Void + ) -> Future { let future = Future() - self.submit(after: after) { end in + submit(after: after) { end in future.onSet { end() } @@ -66,7 +68,7 @@ public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor do { let resolver = FutureResolver(future) try closure(resolver) - } catch let error { + } catch { future.set(error) } } @@ -77,8 +79,9 @@ public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor /// /// - Parameter closure: The closure to be executed. An error can be thrown. /// - Returns: A future wrapping the error, if thrown. - @discardableResult public func submit(after: DispatchTime, _ closure: @escaping () throws -> Void) -> Future { - return self.submit(after: after) { resolver in + @discardableResult public func submit(after: DispatchTime, + _ closure: @escaping () throws -> Void) -> Future { + return submit(after: after) { resolver in try closure() resolver.set() } @@ -87,22 +90,22 @@ public final class DelayedMainQueueExecutor: MainDirectExecutor, DelayedExecutor // /// Executes on the main queue asynchronously. -/// However, if the submit is called in the main thread, the submitted closure is directly called as in a DirectExecutor. +/// However, if the submit is called in the main thread, the submitted closure is directly called as in a +// DirectExecutor. /// public class MainDirectExecutor: Executor { - public let name: String? = "com.mobilejazz.executor.main-direct" public var executing: Bool = false - public init() { } + public init() {} public func submit(_ closure: @escaping (@escaping () -> Void) -> Void) { if Thread.isMainThread { - self.executing = true + executing = true let sempahore = DispatchSemaphore(value: 0) closure { sempahore.signal() } sempahore.wait() - self.executing = false + executing = false } else { DispatchQueue.main.async { self.executing = true diff --git a/Sources/Harmony/Future/Executor/DispatchQueueExecutor.swift b/Sources/Harmony/Future/Executor/DispatchQueueExecutor.swift index 1d5d2349..e2eaa0b4 100644 --- a/Sources/Harmony/Future/Executor/DispatchQueueExecutor.swift +++ b/Sources/Harmony/Future/Executor/DispatchQueueExecutor.swift @@ -22,7 +22,6 @@ private let executingKey = DispatchSpecificKey() /// DispatchQueue Executor extension. /// extension DispatchQueue: Executor { - public var name: String? { return label } public var executing: Bool { @@ -44,7 +43,6 @@ extension DispatchQueue: Executor { /// GCD-based executor /// public class DispatchQueueExecutor: Executor { - /// The queue type /// /// - serialQueue: Serial queue @@ -67,7 +65,8 @@ public class DispatchQueueExecutor: Executor { /// Convenience initializer /// /// - Parameter type: Queue type - public convenience init(_ type: QueueType = .serial, name: String = OperationQueueExecutor.nextExecutorName()) { + public convenience init(_ type: QueueType = .serial, + name: String = OperationQueueExecutor.nextExecutorName()) { switch type { case .serial: let queue = DispatchQueue(label: name) diff --git a/Sources/Harmony/Future/Executor/Executor.swift b/Sources/Harmony/Future/Executor/Executor.swift index bf396447..261b4763 100644 --- a/Sources/Harmony/Future/Executor/Executor.swift +++ b/Sources/Harmony/Future/Executor/Executor.swift @@ -28,7 +28,8 @@ public protocol Executor { /// Submits a closure for its execution /// - /// - Parameter closure: The code to be executed. The closure must call its subclosure after completing (either sync or async) + /// - Parameter closure: The code to be executed. The closure must call its subclosure after completing (either + // sync or async) /// - Returns: Nothing (Void) func submit(_ closure: @escaping (@escaping () -> Void) -> Void) } @@ -37,31 +38,32 @@ public protocol Executor { /// Refined type of Executor that delays execution of a closure /// public protocol DelayedExecutor: Executor { - /// Submits a closure for execution later in time /// - Parameters: /// - after: amount of time elapsed before the closure gets executed - /// - closure: The code to be executed. The closure must call its subclosure after completing (either sync or async) + /// - closure: The code to be executed. The closure must call its subclosure after completing (either sync or + // async) /// - Returns: Nothing (Void) func submit(after: DispatchTime, _ closure: @escaping (@escaping () -> Void) -> Void) /// Submits a closure for execution later in time /// - Parameters: /// - after: amount of time elapsed before the closure gets executed - /// - closure: The code to be executed. The closure must call its subclosure after completing (either sync or async) + /// - closure: The code to be executed. The closure must call its subclosure after completing (either sync or + // async) /// - Returns: Nothing (Void) @discardableResult - func submit(after: DispatchTime, _ closure: @escaping () throws -> Void) -> Future + func submit(after: DispatchTime, _ closure: @escaping () throws -> Void) -> Future } private let lock = NSLock() private var counter: Int = 0 -extension Executor { +public extension Executor { /// Creates a unique executor name /// /// - Returns: An executor name - static public func nextExecutorName() -> String { + static func nextExecutorName() -> String { lock.lock() counter += 1 defer { lock.unlock() } diff --git a/Sources/Harmony/Future/Executor/ExecutorFactory.swift b/Sources/Harmony/Future/Executor/ExecutorFactory.swift index cca37010..c0d3ff59 100644 --- a/Sources/Harmony/Future/Executor/ExecutorFactory.swift +++ b/Sources/Harmony/Future/Executor/ExecutorFactory.swift @@ -16,7 +16,6 @@ import Foundation public class ExecutorFactory { - public enum Scope { case none case string(String) @@ -37,7 +36,7 @@ public class ExecutorFactory { switch scope { case .none: return builder(name) - case .string(let value): + case let .string(value): if let executor = stringScope[value] { return executor } else { @@ -45,7 +44,7 @@ public class ExecutorFactory { stringScope[value] = executor return executor } - case .type(let value): + case let .type(value): if let executor = typeScope[value] { return executor } else { @@ -53,7 +52,7 @@ public class ExecutorFactory { typeScope[value] = executor return executor } - case .integer(let value): + case let .integer(value): if let executor = integerScope[value] { return executor } else { diff --git a/Sources/Harmony/Future/Executor/OperationQueueExecutor.swift b/Sources/Harmony/Future/Executor/OperationQueueExecutor.swift index 0969976e..3e5e4a04 100644 --- a/Sources/Harmony/Future/Executor/OperationQueueExecutor.swift +++ b/Sources/Harmony/Future/Executor/OperationQueueExecutor.swift @@ -20,7 +20,6 @@ import Foundation /// OperationQueue Executor extension. /// extension OperationQueue: Executor { - public var executing: Bool { return operationCount > 0 } public func submit(_ closure: @escaping (@escaping () -> Void) -> Void) { @@ -36,7 +35,6 @@ extension OperationQueue: Executor { /// OperationQueue based executor /// public class OperationQueueExecutor: Executor { - /// The operation queue public let operationQueue: OperationQueue @@ -64,13 +62,14 @@ public class OperationQueueExecutor: Executor { /// - Parameters: /// - type: The type of queue /// - name: The name of the queue - public convenience init (_ type: QueueType = .serial, name: String = OperationQueueExecutor.nextExecutorName()) { + public convenience init(_ type: QueueType = .serial, + name: String = OperationQueueExecutor.nextExecutorName()) { let operationQueue = OperationQueue() operationQueue.name = name switch type { case .serial: operationQueue.maxConcurrentOperationCount = 1 - case .concurrent(let count): + case let .concurrent(count): operationQueue.maxConcurrentOperationCount = count } self.init(operationQueue) diff --git a/Sources/Harmony/Future/Future/Executor+Future.swift b/Sources/Harmony/Future/Future/Executor+Future.swift index 239363ca..0bb3783d 100644 --- a/Sources/Harmony/Future/Future/Executor+Future.swift +++ b/Sources/Harmony/Future/Future/Executor+Future.swift @@ -16,16 +16,15 @@ import Foundation -extension Executor { - +public extension Executor { /// Submits a closure for its execution with a future to be filled. /// Note that the future returned is not the same as the future privded in the closure. /// /// - Parameter closure: The closure to be executed. The future must be filled. /// - Returns: A future wrapping the result. - @discardableResult public func submit(_ closure: @escaping (FutureResolver) throws -> Void) -> Future { + @discardableResult func submit(_ closure: @escaping (FutureResolver) throws -> Void) -> Future { let future = Future() - self.submit { end in + submit { end in future.onSet { end() } @@ -33,7 +32,7 @@ extension Executor { do { let resolver = FutureResolver(future) try closure(resolver) - } catch let error { + } catch { future.set(error) } } @@ -44,8 +43,8 @@ extension Executor { /// /// - Parameter closure: The closure to be executed. An error can be thrown. /// - Returns: A future wrapping the error, if thrown. - @discardableResult public func submit(_ closure: @escaping () throws -> Void) -> Future { - return self.submit { resolver in + @discardableResult func submit(_ closure: @escaping () throws -> Void) -> Future { + return submit { resolver in try closure() resolver.set() } diff --git a/Sources/Harmony/Future/Future/Future+Batch.swift b/Sources/Harmony/Future/Future/Future+Batch.swift index 95a6b839..fdfd30cf 100644 --- a/Sources/Harmony/Future/Future/Future+Batch.swift +++ b/Sources/Harmony/Future/Future/Future+Batch.swift @@ -16,14 +16,14 @@ import Foundation -extension Future { +public extension Future { // swiftlint:disable large_tuple /// Creates a new future from a sequence of futures. /// /// - Parameter futures: A sequence of futures. /// - Returns: The future batch. - public static func batch(_ futures: Future ...) -> Future<[T]> { + static func batch(_ futures: Future ...) -> Future<[T]> { return Future.batch(futures) } @@ -31,7 +31,7 @@ extension Future { /// /// - Parameter futures: An array of futures. /// - Returns: The future batch. - public static func batch(_ futures: [Future]) -> Future<[T]> { + static func batch(_ futures: [Future]) -> Future<[T]> { if futures.isEmpty { return Future<[T]>([]) } @@ -46,7 +46,7 @@ extension Future { if future.state != .sent { if dict.count == futures.count { var array: [T] = [] - for idx in 0..(_ futureK: Future) -> Future<(T, K)> { + func zip(_ futureK: Future) -> Future<(T, K)> { return flatMap { valueT in - return futureK.map { valueK in - return (valueT, valueK) + futureK.map { valueK in + (valueT, valueK) } } } /// Creates a new future that holds the tupple of results - public func zip(_ futureK: Future, _ futureL: Future) -> Future<(T, K, L)> { + func zip(_ futureK: Future, _ futureL: Future) -> Future<(T, K, L)> { return zip(futureK).flatMap { valueTK in - return futureL.map { valueL in - return (valueTK.0, valueTK.1, valueL) + futureL.map { valueL in + (valueTK.0, valueTK.1, valueL) } } } /// Creates a new future that holds the tupple of results - public func zip(_ futureK: Future, _ futureL: Future, _ futureM: Future) -> Future<(T, K, L, M)> { + func zip(_ futureK: Future, _ futureL: Future, _ futureM: Future) -> Future<(T, K, L, M)> { return zip(futureK, futureL).flatMap { valueTKL in - return futureM.map { valueM in - return (valueTKL.0, valueTKL.1, valueTKL.2, valueM) + futureM.map { valueM in + (valueTKL.0, valueTKL.1, valueTKL.2, valueM) } } } /// Unzips a 2-tuple future into two futures - public func unzip() -> (Future, Future) where T == (K, L) { + func unzip() -> (Future, Future) where T == (K, L) { let futureK = Future() let futureL = Future() - resolve(success: {tuple in + resolve(success: { tuple in futureK.set(tuple.0) futureL.set(tuple.1) }, failure: { error in @@ -104,11 +104,11 @@ extension Future { } /// Unzips a 3-tuple future into three futures - public func unzip() -> (Future, Future, Future) where T == (K, L, M) { + func unzip() -> (Future, Future, Future) where T == (K, L, M) { let futureK = Future() let futureL = Future() let futureM = Future() - resolve(success: {tuple in + resolve(success: { tuple in futureK.set(tuple.0) futureL.set(tuple.1) futureM.set(tuple.2) @@ -121,12 +121,12 @@ extension Future { } /// Unzips a 4-tuple future into four futures - public func unzip() -> (Future, Future, Future, Future) where T == (K, L, M, N) { + func unzip() -> (Future, Future, Future, Future) where T == (K, L, M, N) { let futureK = Future() let futureL = Future() let futureM = Future() let futureN = Future() - resolve(success: {tuple in + resolve(success: { tuple in futureK.set(tuple.0) futureL.set(tuple.1) futureM.set(tuple.2) @@ -141,9 +141,10 @@ extension Future { } /// Collapses a 2-tuple future into a single value future - public func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L) -> Z) -> Future where T == (K, L) { + func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L) -> Z) -> Future + where T == (K, L) { return Future { resolver in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { resolver.set(closure(tuple.0, tuple.1)) } }, failure: { error in executor.submit { resolver.set(error) } @@ -152,9 +153,10 @@ extension Future { } /// Collapses a 3-tuple future into a single value future - public func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L, M) -> Z) -> Future where T == (K, L, M) { + func collapse(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K, L, M) -> Z) -> Future where T == (K, L, M) { return Future { resolver in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { resolver.set(closure(tuple.0, tuple.1, tuple.2)) } }, failure: { error in executor.submit { resolver.set(error) } @@ -163,9 +165,10 @@ extension Future { } /// Collapses a 4-tuple future into a single value future - public func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L, M, N) -> Z) -> Future where T == (K, L, M, N) { + func collapse(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K, L, M, N) -> Z) -> Future where T == (K, L, M, N) { return Future { resolver in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { resolver.set(closure(tuple.0, tuple.1, tuple.2, tuple.3)) } }, failure: { error in executor.submit { resolver.set(error) } diff --git a/Sources/Harmony/Future/Future/Future+Extensions.swift b/Sources/Harmony/Future/Future/Future+Extensions.swift index 267d88b4..68ce6121 100644 --- a/Sources/Harmony/Future/Future/Future+Extensions.swift +++ b/Sources/Harmony/Future/Future/Future+Extensions.swift @@ -14,8 +14,8 @@ // limitations under the License. // -import Foundation import CoreGraphics +import Foundation // ------------ Basic Foundation Types ------------ // diff --git a/Sources/Harmony/Future/Future/Future+Functional.swift b/Sources/Harmony/Future/Future/Future+Functional.swift index acec3e9f..eb8d67e3 100644 --- a/Sources/Harmony/Future/Future/Future+Functional.swift +++ b/Sources/Harmony/Future/Future/Future+Functional.swift @@ -17,7 +17,6 @@ import Foundation public extension Future { - /// Maps the value and return a new future with the value mapped /// /// - Parameters: @@ -28,7 +27,7 @@ public extension Future { return Future { resolver in resolve(success: { value in executor.submit { - do { resolver.set(try transform(value)) } catch let error { resolver.set(error) } + do { resolver.set(try transform(value)) } catch { resolver.set(error) } } }, failure: { error in executor.submit { resolver.set(error) } @@ -44,7 +43,7 @@ public extension Future { /// - Returns: A error-mapped chained future func mapError(_ executor: Executor = DirectExecutor(), _ transform: @escaping (Error) -> Error) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } }, failure: { error in executor.submit { resolver.set(transform(error)) } @@ -58,11 +57,12 @@ public extension Future { /// - executor: An optional executor to execute the closure. /// - closure: The flatmap closure /// - Returns: A chained future - func flatMap(_ executor: Executor = DirectExecutor(), _ closure: @escaping (T) throws -> Future) -> Future { + func flatMap(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (T) throws -> Future) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { - do { resolver.set(try closure(value)) } catch let error { resolver.set(error) } + do { resolver.set(try closure(value)) } catch { resolver.set(error) } } }, failure: { error in executor.submit { resolver.set(error) } @@ -77,7 +77,7 @@ public extension Future { /// - Returns: The incoming future chained to the current one func chain(_ future: Future) -> Future { return flatMap { _ in - return future + future } } @@ -87,13 +87,14 @@ public extension Future { /// - executor: An optional executor to execute the closure. /// - closure: The recover closure /// - Returns: A chained future - func recover(_ executor: Executor = DirectExecutor(), _ closure: @escaping (Error) throws -> Future) -> Future { + func recover(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (Error) throws -> Future) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } }, failure: { error in executor.submit { - do { resolver.set(try closure(error)) } catch let error { resolver.set(error) } + do { resolver.set(try closure(error)) } catch { resolver.set(error) } } }) } @@ -106,9 +107,10 @@ public extension Future { /// - executor: An optional executor to execute the closure. /// - closure: The recover closure /// - Returns: A chained future - func recover(if errorType: E.Type, _ executor: Executor = DirectExecutor(), _ closure: @escaping (E) throws -> Future) -> Future { + func recover(if _: E.Type, _ executor: Executor = DirectExecutor(), + _ closure: @escaping (E) throws -> Future) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } }, failure: { error in executor.submit { @@ -116,7 +118,7 @@ public extension Future { case let error as E: do { resolver.set(try closure(error)) - } catch let error { + } catch { resolver.set(error) } default: @@ -136,7 +138,7 @@ public extension Future { @discardableResult func onCompletion(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> Void) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { closure() resolver.set(value) @@ -158,12 +160,12 @@ public extension Future { /// - Returns: A chained future func filter(_ executor: Executor = DirectExecutor(), _ closure: @escaping (T) throws -> Void) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { do { try closure(value) resolver.set(value) - } catch let error { + } catch { resolver.set(error) } } diff --git a/Sources/Harmony/Future/Future/Future+Operators.swift b/Sources/Harmony/Future/Future/Future+Operators.swift index f0d5d15a..dab411b6 100644 --- a/Sources/Harmony/Future/Future/Future+Operators.swift +++ b/Sources/Harmony/Future/Future/Future+Operators.swift @@ -17,16 +17,17 @@ import Foundation /// Operator + overriding -public func +(left: Future, right: Future) -> Future<(T, K)> { +public func + (left: Future, right: Future) -> Future<(T, K)> { return left.zip(right) } precedencegroup MapPrecedance { associativity: left } -infix operator <^> : MapPrecedance + +infix operator <^>: MapPrecedance /// Map operator -public func <^>(future: Future, map: @escaping (T) -> K) -> Future { +public func <^> (future: Future, map: @escaping (T) -> K) -> Future { return future.map { value in map(value) } } diff --git a/Sources/Harmony/Future/Future/Future+Optionals.swift b/Sources/Harmony/Future/Future/Future+Optionals.swift index b8f08385..3c9c62de 100644 --- a/Sources/Harmony/Future/Future/Future+Optionals.swift +++ b/Sources/Harmony/Future/Future/Future+Optionals.swift @@ -20,7 +20,6 @@ import Foundation public class NilValueError: Error { public init() {} } public extension Future { - /// Unwrapes a future of an optional type, returning a future of a non-optional type /// /// - Returns: A chained future. @@ -37,14 +36,15 @@ public extension Future { /// /// - Returns: An optional typed future func optional() -> Future { - return self.map { $0 as T? } + return map { $0 as T? } } /// Calls the closure when the future is resolved with a nil value. /// /// - Parameter closure: The closure that will return a non-nil value. /// - Returns: A future with a non-optional type. - func fill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> K) -> Future where T == K? { + func fill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> K) -> Future + where T == K? { return flatMap(executor) { value in guard let value = value else { return Future(closure()) @@ -57,7 +57,8 @@ public extension Future { /// /// - Parameter closure: The closure that will return a non-optional future. /// - Returns: A future with a non-optional type. - func flatFill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> Future) -> Future where T == K? { + func flatFill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> Future) -> Future + where T == K? { return flatMap(executor) { value in guard let value = value else { return Future(closure()) @@ -69,7 +70,8 @@ public extension Future { /// Performs a map of an optional future when the value is defined. /// /// - Returns: A chained future. - func unwrappedMap(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K) -> P) -> Future where T == K? { + func unwrappedMap(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K) -> P) -> Future + where T == K? { return flatMap(executor) { value in guard let value = value else { return Future(nil) diff --git a/Sources/Harmony/Future/Future/Future+Time.swift b/Sources/Harmony/Future/Future/Future+Time.swift index 97be70aa..76a4cd37 100644 --- a/Sources/Harmony/Future/Future/Future+Time.swift +++ b/Sources/Harmony/Future/Future/Future+Time.swift @@ -17,7 +17,6 @@ import Foundation public extension Future { - /// Adds a delay to the then call. /// /// - Parameters: @@ -31,7 +30,7 @@ public extension Future { return Future { resolver in queue.asyncAfter(deadline: .now() + interval) { - self.resolve(success: {value in + self.resolve(success: { value in resolver.set(value) }, failure: { error in resolver.set(error) @@ -52,7 +51,7 @@ public extension Future { return Future { resolver in Thread.sleep(forTimeInterval: interval) - self.resolve(success: {value in + self.resolve(success: { value in resolver.set(value) }, failure: { error in resolver.set(error) @@ -69,7 +68,7 @@ public extension Future { func after(_ deadline: DispatchTime, queue: DispatchQueue) -> Future { return Future { resolver in queue.asyncAfter(deadline: deadline) { - self.resolve(success: {value in + self.resolve(success: { value in resolver.set(value) }, failure: { error in resolver.set(error) diff --git a/Sources/Harmony/Future/Future/Future.swift b/Sources/Harmony/Future/Future/Future.swift index 5cafe4b0..2b9c9b4f 100644 --- a/Sources/Harmony/Future/Future/Future.swift +++ b/Sources/Harmony/Future/Future/Future.swift @@ -23,22 +23,21 @@ private struct FutureError: Error { } } -extension FutureError { +private extension FutureError { /// Future content has already been set - fileprivate static let thenAlreadySet = FutureError("Then already set: cannot set a new then closure once is already set.") + static let thenAlreadySet = FutureError("Then already set: cannot set a new then closure once is already set.") /// Future content has already been set - fileprivate static let alreadySent = FutureError("Future is already sent.") + static let alreadySent = FutureError("Future is already sent.") /// Future content has already been set - fileprivate static let missingLambda = FutureError("Future cannot be sent as the then clousre hasn't been defined") + static let missingLambda = FutureError("Future cannot be sent as the then clousre hasn't been defined") } /// /// A FutureResolver resolves a Future. /// public struct FutureResolver { - private var future: Future /// Main initializer @@ -63,16 +62,17 @@ public struct FutureResolver { self.future.set(future) } - /// Sets the future with a value if not error. Either the value or the error must be provided, otherwise a crash will happen. + /// Sets the future with a value if not error. Either the value or the error must be provided, otherwise a crash + // will happen. /// Note: error is prioritary, and if not error the value will be used. public func set(value: T?, error: Error?) { future.set(value: value, error: error) } } -extension FutureResolver where T==Void { +public extension FutureResolver where T == Void { /// Sets the future with a void value - public func set() { + func set() { future.set() } } @@ -117,9 +117,9 @@ public class Future { @discardableResult public func get() throws -> T { switch self { - case .value(let v): + case let .value(v): return v - case .error(let e): + case let .error(e): throw e } } @@ -128,9 +128,9 @@ public class Future { @discardableResult public func get(error: inout Error?) -> T? { switch self { - case .value(let v): + case let .value(v): return v - case .error(let e): + case let .error(e): error = e return nil } @@ -148,7 +148,7 @@ public class Future { private var failure: ((_ error: Error) -> Void)? /// Default initializer - public init() { } + public init() {} /// Value initializer public init(_ value: T) { @@ -171,7 +171,11 @@ public class Future { } /// Future initializer - public init(_ observable: Observable, ignoreErrors: Bool = false, atEventPassingTest closure: @escaping (T) -> Bool) { + public init( + _ observable: Observable, + ignoreErrors: Bool = false, + atEventPassingTest closure: @escaping (T) -> Bool + ) { set(observable, ignoreErrors: ignoreErrors, atEventPassingTest: closure) } @@ -180,7 +184,7 @@ public class Future { do { let resolver = FutureResolver(self) try closure(resolver) - } catch let error { + } catch { set(error) } } @@ -190,7 +194,7 @@ public class Future { do { let future = try closure() self.init(future) - } catch let error { + } catch { self.init(error) } } @@ -200,7 +204,7 @@ public class Future { do { let value = try closure() self.init(value) - } catch let error { + } catch { self.init(error) } } @@ -239,7 +243,8 @@ public class Future { /// /// - Parameters: /// - observable: The incoming observable - /// - eventIdx: The event index to set the future. Use 0 to indicate the following event (or the eixsting one if the observer is already resolved). Default is 0. + /// - eventIdx: The event index to set the future. Use 0 to indicate the following event (or the eixsting one + // if the observer is already resolved). Default is 0. public func set(_ observable: Observable, atEvent eventIdx: Int = 0) { var obs: Observable? = observable.hub.subscribe() var idx = eventIdx @@ -264,7 +269,11 @@ public class Future { /// - observable: The incoming observable /// - closure: The test closure /// - ignoreErrors: if true, all errors will be ignored (and the future is not resolved). Default is false. - public func set(_ observable: Observable, ignoreErrors: Bool = false, atEventPassingTest closure: @escaping (T) -> Bool) { + public func set( + _ observable: Observable, + ignoreErrors: Bool = false, + atEventPassingTest closure: @escaping (T) -> Bool + ) { var obs: Observable? = observable.hub.subscribe() obs!.resolve(success: { value in if closure(value) { @@ -279,7 +288,8 @@ public class Future { }) } - /// Sets the future with a value if not error. Either the value or the error must be provided, otherwise a crash will happen. + /// Sets the future with a value if not error. Either the value or the error must be provided, otherwise a crash + // will happen. /// Note: error is prioritary, and if not error the value will be used. public func set(value: T?, error: Error?) { if _result != nil || state == .sent { @@ -330,12 +340,13 @@ public class Future { } /// Closure called right after content is set, without waiting the then closure. - /// Note that multiple calls to this method are discouraged, resulting with only one onContentSet closure being called. + /// Note that multiple calls to this method are discouraged, resulting with only one onContentSet closure being + // called. /// Note too that if the future has already been sent, this closure is not called. /// /// - Parameter closure: The code to be executed public func onSet(_ closure: @escaping () -> Void) { - onContentSet = { (_, _) in + onContentSet = { _, _ in closure() } } @@ -352,7 +363,6 @@ public class Future { /// Then closure: delivers the value or the error internal func resolve(success: @escaping (T) -> Void = { _ in }, failure: @escaping (Error) -> Void = { _ in }) { - if self.success != nil || self.failure != nil { fatalError(FutureError.thenAlreadySet.description) } @@ -372,20 +382,18 @@ public class Future { /// Deliver the result syncrhonously. This method might block the calling thread. /// Note that the result can only be delivered once public var result: Result { - get { - switch state { - case .waitingThen: - state = .sent - return _result! - case .blank: - semaphore = DispatchSemaphore(value: 0) - semaphore!.wait() - return self.result - case .waitingContent: - fatalError(FutureError.thenAlreadySet.description) - case .sent: - fatalError(FutureError.alreadySent.description) - } + switch state { + case .waitingThen: + state = .sent + return _result! + case .blank: + semaphore = DispatchSemaphore(value: 0) + semaphore!.wait() + return self.result + case .waitingContent: + fatalError(FutureError.thenAlreadySet.description) + case .sent: + fatalError(FutureError.alreadySent.description) } } @@ -398,7 +406,7 @@ public class Future { @discardableResult public func then(_ executor: Executor = MainDirectExecutor(), _ success: @escaping (T) -> Void) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { success(value) resolver.set(value) @@ -418,9 +426,10 @@ public class Future { /// - failure: The fail closure. /// - Returns: A chained future @discardableResult - public func fail(_ executor: Executor = MainDirectExecutor(), _ failure: @escaping (Error) -> Void) -> Future { + public func fail(_ executor: Executor = MainDirectExecutor(), + _ failure: @escaping (Error) -> Void) -> Future { return Future { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } @@ -446,13 +455,13 @@ public class Future { private func send() { switch _result! { - case .error(let error): + case let .error(error): guard let failure = failure else { print(FutureError.missingLambda.description) return } failure(error) - case .value(let value): + case let .value(value): guard let success = success else { print(FutureError.missingLambda.description) return @@ -460,8 +469,8 @@ public class Future { success(value) } - self.success = nil - self.failure = nil + success = nil + failure = nil } // Private lock method @@ -480,9 +489,9 @@ extension Future: CustomStringConvertible, CustomDebugStringConvertible { return "Empty future. Waiting for value, error and then closure." case .waitingThen: switch _result! { - case .error(let error): + case let .error(error): return "Future waiting for then closure with error set to: \(error)" - case .value(let value): + case let .value(value): return "Future waiting for then closure with value set to: \(value)" } case .waitingContent: @@ -490,9 +499,9 @@ extension Future: CustomStringConvertible, CustomDebugStringConvertible { case .sent: if let result = _result { switch result { - case .error(let error): + case let .error(error): return "Future sent with error: \(error)" - case .value(let value): + case let .value(value): return "Future sent with value: \(value)" } } else { @@ -500,13 +509,14 @@ extension Future: CustomStringConvertible, CustomDebugStringConvertible { } } } + public var debugDescription: String { return description } } -extension Future where T==Void { - public func set() { - set(Void()) +public extension Future where T == Void { + func set() { + set(()) } } diff --git a/Sources/Harmony/Future/Observable/Observable+Batch.swift b/Sources/Harmony/Future/Observable/Observable+Batch.swift index 5409529b..68be0f18 100644 --- a/Sources/Harmony/Future/Observable/Observable+Batch.swift +++ b/Sources/Harmony/Future/Observable/Observable+Batch.swift @@ -20,7 +20,8 @@ public extension Observable { // swiftlint:disable large_tuple /// Creates a new observable from a sequence of observables. - /// Note that the batch will be delivered once all observables have resolved at least once. After that, the batch will resolve on all new resolves. Each single error will be delivered independently. + /// Note that the batch will be delivered once all observables have resolved at least once. After that, the + // batch will resolve on all new resolves. Each single error will be delivered independently. /// /// - Parameter futures: A sequence of observables. /// - Returns: The observable batch. @@ -29,7 +30,8 @@ public extension Observable { } /// Creates a new observable from an array of observables. - /// Note that the batch will be delivered once all observables have resolved at least once. After that, the batch will resolve on all new resolves. Each single error will be delivered independently. + /// Note that the batch will be delivered once all observables have resolved at least once. After that, the + // batch will resolve on all new resolves. Each single error will be delivered independently. /// /// - Parameter futures: An array of observables. /// - Returns: The observable batch. @@ -47,7 +49,7 @@ public extension Observable { dict[idx] = value if dict.count == futures.count { var array: [T] = [] - for idx in 0..(_ observableK: Observable) -> Observable<(T, K)> { return flatMap { valueT in - return observableK.map { valueK in - return (valueT, valueK) + observableK.map { valueK in + (valueT, valueK) } } } @@ -74,17 +76,18 @@ public extension Observable { /// Creates a new observable that holds the tupple of results func zip(_ observableK: Observable, _ observableL: Observable) -> Observable<(T, K, L)> { return zip(observableK).flatMap { valueTK in - return observableL.map { valueL in - return (valueTK.0, valueTK.1, valueL) + observableL.map { valueL in + (valueTK.0, valueTK.1, valueL) } } } /// Creates a new observable that holds the tupple of results - func zip(_ observableK: Observable, _ observableL: Observable, _ observableM: Observable) -> Observable<(T, K, L, M)> { + func zip(_ observableK: Observable, _ observableL: Observable, + _ observableM: Observable) -> Observable<(T, K, L, M)> { return zip(observableK, observableL).flatMap { valueTKL in - return observableM.map { valueM in - return (valueTKL.0, valueTKL.1, valueTKL.2, valueM) + observableM.map { valueM in + (valueTKL.0, valueTKL.1, valueTKL.2, valueM) } } } @@ -93,7 +96,7 @@ public extension Observable { func unzip() -> (Observable, Observable) where T == (K, L) { let observableK = Observable() let observableL = Observable() - resolve(success: {tuple in + resolve(success: { tuple in observableK.set(tuple.0) observableL.set(tuple.1) }, failure: { error in @@ -108,7 +111,7 @@ public extension Observable { let observableK = Observable() let observableL = Observable() let observableM = Observable() - resolve(success: {tuple in + resolve(success: { tuple in observableK.set(tuple.0) observableL.set(tuple.1) observableM.set(tuple.2) @@ -121,12 +124,13 @@ public extension Observable { } /// Unzips a 4-tuple observable into four observables - func unzip() -> (Observable, Observable, Observable, Observable) where T == (K, L, M, N) { + func unzip() -> (Observable, Observable, Observable, Observable) + where T == (K, L, M, N) { let observableK = Observable() let observableL = Observable() let observableM = Observable() let observableN = Observable() - resolve(success: {tuple in + resolve(success: { tuple in observableK.set(tuple.0) observableL.set(tuple.1) observableM.set(tuple.2) @@ -141,9 +145,10 @@ public extension Observable { } /// Collapses a 2-tuple observable into a single value observable - func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L) -> Z) -> Observable where T == (K, L) { + func collapse(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K, L) -> Z) -> Observable where T == (K, L) { return Observable { observable in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { observable.set(closure(tuple.0, tuple.1)) } }, failure: { error in executor.submit { observable.set(error) } @@ -152,9 +157,10 @@ public extension Observable { } /// Collapses a 3-tuple observable into a single value observable - func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L, M) -> Z) -> Observable where T == (K, L, M) { + func collapse(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K, L, M) -> Z) -> Observable where T == (K, L, M) { return Observable { observable in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { observable.set(closure(tuple.0, tuple.1, tuple.2)) } }, failure: { error in executor.submit { observable.set(error) } @@ -163,9 +169,10 @@ public extension Observable { } /// Collapses a 4-tuple observable into a single value observable - func collapse(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K, L, M, N) -> Z) -> Observable where T == (K, L, M, N) { + func collapse(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K, L, M, N) -> Z) -> Observable where T == (K, L, M, N) { return Observable { observable in - resolve(success: {tuple in + resolve(success: { tuple in executor.submit { observable.set(closure(tuple.0, tuple.1, tuple.2, tuple.3)) } }, failure: { error in executor.submit { observable.set(error) } diff --git a/Sources/Harmony/Future/Observable/Observable+Extensions.swift b/Sources/Harmony/Future/Observable/Observable+Extensions.swift index b8088bd8..0452285b 100644 --- a/Sources/Harmony/Future/Observable/Observable+Extensions.swift +++ b/Sources/Harmony/Future/Observable/Observable+Extensions.swift @@ -14,8 +14,8 @@ // limitations under the License. // -import Foundation import CoreGraphics +import Foundation // ------------ Basic Foundation Types ------------ // diff --git a/Sources/Harmony/Future/Observable/Observable+Functional.swift b/Sources/Harmony/Future/Observable/Observable+Functional.swift index 8cacaf39..47711257 100644 --- a/Sources/Harmony/Future/Observable/Observable+Functional.swift +++ b/Sources/Harmony/Future/Observable/Observable+Functional.swift @@ -17,7 +17,6 @@ import Foundation public extension Observable { - /// Maps the value and return a new observable with the value mapped /// /// - Parameters: @@ -28,7 +27,7 @@ public extension Observable { return Observable(parent: self) { resolver in resolve(success: { value in executor.submit { - do { resolver.set(try transform(value)) } catch let error { resolver.set(error) } + do { resolver.set(try transform(value)) } catch { resolver.set(error) } } }, failure: { error in executor.submit { resolver.set(error) } @@ -42,7 +41,8 @@ public extension Observable { /// - executor: An optional executor to execute the closure. /// - transform: The map closure /// - Returns: A error-mapped chained future - func mapError(_ executor: Executor = DirectExecutor(), _ transform: @escaping (Error) -> Error) -> Observable { + func mapError(_ executor: Executor = DirectExecutor(), + _ transform: @escaping (Error) -> Error) -> Observable { return Observable(parent: self) { resolver in resolve(success: { value in executor.submit { resolver.set(value) } @@ -58,11 +58,12 @@ public extension Observable { /// - executor: An optional executor to execute the closure. /// - closure: The flatmap closure /// - Returns: A chained observable - func flatMap(_ executor: Executor = DirectExecutor(), _ closure: @escaping (T) throws -> Observable) -> Observable { + func flatMap(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (T) throws -> Observable) -> Observable { return Observable(parent: self) { resolver in resolve(success: { value in executor.submit { - do { resolver.set(try closure(value)) } catch let error { resolver.set(error) } + do { resolver.set(try closure(value)) } catch { resolver.set(error) } } }, failure: { error in executor.submit { resolver.set(error) } @@ -77,7 +78,7 @@ public extension Observable { /// - Returns: The incoming observable chained to the current one func chain(_ observable: Observable) -> Observable { return flatMap { _ in - return observable + observable } } @@ -87,13 +88,14 @@ public extension Observable { /// - executor: An optional executor to execute the closure. /// - closure: The recover closure /// - Returns: A chained observable - func recover(_ executor: Executor = DirectExecutor(), _ closure: @escaping (Error) throws -> Observable) -> Observable { + func recover(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (Error) throws -> Observable) -> Observable { return Observable(parent: self) { resolver in resolve(success: { value in executor.submit { resolver.set(value) } }, failure: { error in executor.submit { - do { resolver.set(try closure(error)) } catch let error { resolver.set(error) } + do { resolver.set(try closure(error)) } catch { resolver.set(error) } } }) } @@ -106,9 +108,10 @@ public extension Observable { /// - executor: An optional executor to execute the closure. /// - closure: The recover closure /// - Returns: A chained observable - func recover(if errorType: E.Type, _ executor: Executor = DirectExecutor(), _ closure: @escaping (E) throws -> Observable) -> Observable { + func recover(if _: E.Type, _ executor: Executor = DirectExecutor(), + _ closure: @escaping (E) throws -> Observable) -> Observable { return Observable(parent: self) { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } }, failure: { error in executor.submit { @@ -116,7 +119,7 @@ public extension Observable { case let error as E: do { resolver.set(try closure(error)) - } catch let error { + } catch { resolver.set(error) } default: @@ -156,14 +159,15 @@ public extension Observable { /// - executor: An optional executor to execute the closure. /// - closure: The filter closure. Throw an error to replace it's value for an error. /// - Returns: A chained observable - func filter(_ executor: Executor = DirectExecutor(), _ closure: @escaping (T) throws -> Void) -> Observable { + func filter(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (T) throws -> Void) -> Observable { return Observable(parent: self) { resolver in resolve(success: { value in executor.submit { do { try closure(value) resolver.set(value) - } catch let error { + } catch { resolver.set(error) } } diff --git a/Sources/Harmony/Future/Observable/Observable+Optionals.swift b/Sources/Harmony/Future/Observable/Observable+Optionals.swift index 895a08c9..8842e567 100644 --- a/Sources/Harmony/Future/Observable/Observable+Optionals.swift +++ b/Sources/Harmony/Future/Observable/Observable+Optionals.swift @@ -17,7 +17,6 @@ import Foundation public extension Observable { - /// Unwrapes a observable of an optional type, returning a observable of a non-optional type /// /// - Returns: A chained observable. @@ -34,14 +33,15 @@ public extension Observable { /// /// - Returns: An optional typed observable func optional() -> Observable { - return self.map { $0 as T? } + return map { $0 as T? } } /// Calls the closure when the observable is resolved with a nil value. /// /// - Parameter closure: The closure that will return a non-nil value. /// - Returns: A observable with a non-optional type. - func fill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> K) -> Observable where T == K? { + func fill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> K) -> Observable + where T == K? { return flatMap(executor) { value in guard let value = value else { return Observable(closure()) @@ -54,7 +54,8 @@ public extension Observable { /// /// - Parameter closure: The closure that will return a non-optional observable. /// - Returns: A observable with a non-optional type. - func flatFill(_ executor: Executor = DirectExecutor(), _ closure: @escaping () -> Observable) -> Observable where T == K? { + func flatFill(_ executor: Executor = DirectExecutor(), + _ closure: @escaping () -> Observable) -> Observable where T == K? { return flatMap(executor) { value in guard let value = value else { return Observable(closure()) @@ -66,7 +67,8 @@ public extension Observable { /// Performs a map of an optional observable when the value is defined. /// /// - Returns: A chained observable. - func unwrappedMap(_ executor: Executor = DirectExecutor(), _ closure: @escaping (K) -> P) -> Observable where T == K? { + func unwrappedMap(_ executor: Executor = DirectExecutor(), + _ closure: @escaping (K) -> P) -> Observable where T == K? { return flatMap(executor) { value in guard let value = value else { return Observable(nil) diff --git a/Sources/Harmony/Future/Observable/Observable+Time.swift b/Sources/Harmony/Future/Observable/Observable+Time.swift index 96fbc813..698a3e04 100644 --- a/Sources/Harmony/Future/Observable/Observable+Time.swift +++ b/Sources/Harmony/Future/Observable/Observable+Time.swift @@ -17,7 +17,6 @@ import Foundation public extension Observable { - /// Adds a delay to the then call. /// /// - Parameters: @@ -27,7 +26,7 @@ public extension Observable { func withDelay(_ interval: TimeInterval, queue: DispatchQueue) -> Observable { return Observable(parent: self) { resolver in queue.asyncAfter(deadline: .now() + interval) { [weak self] in - self?.resolve(success: {value in + self?.resolve(success: { value in resolver.set(value) }, failure: { error in resolver.set(error) @@ -65,7 +64,7 @@ public extension Observable { func after(_ deadline: DispatchTime, queue: DispatchQueue) -> Observable { return Observable(parent: self) { resolver in queue.asyncAfter(deadline: deadline) { [weak self] in - self?.resolve(success: {value in + self?.resolve(success: { value in resolver.set(value) }, failure: { error in resolver.set(error) diff --git a/Sources/Harmony/Future/Observable/Observable.swift b/Sources/Harmony/Future/Observable/Observable.swift index 2da45f10..b717a5be 100644 --- a/Sources/Harmony/Future/Observable/Observable.swift +++ b/Sources/Harmony/Future/Observable/Observable.swift @@ -23,19 +23,19 @@ private struct ObservableError: Error { } } -extension ObservableError { +private extension ObservableError { /// Observable content has already been set - fileprivate static let thenAlreadySet = ObservableError("Then already set: cannot set a new then closure once is already set.") + static let thenAlreadySet = + ObservableError("Then already set: cannot set a new then closure once is already set.") /// Observable content has already been set - fileprivate static let missingLambda = ObservableError("Observable cannot be sent as the then clousre hasn't been defined") + static let missingLambda = ObservableError("Observable cannot be sent as the then clousre hasn't been defined") } /// /// A ObservableResolver resolves a Observable. /// public struct ObservableResolver { - private weak var observable: Observable? /// Main initializer @@ -65,27 +65,29 @@ public struct ObservableResolver { observable?.set(future) } - /// Sets the observable with a value if not error. Either the value or the error must be provided, otherwise a crash will happen. + /// Sets the observable with a value if not error. Either the value or the error must be provided, otherwise a + // crash will happen. /// Note: error is prioritary, and if not error the value will be used. public func set(value: T?, error: Error?) { observable?.set(value: value, error: error) } - public func onDeinit(_ closure : @escaping () -> Void) { + public func onDeinit(_ closure: @escaping () -> Void) { observable?.onDeinit(closure) } } -extension ObservableResolver where T==Void { +public extension ObservableResolver where T == Void { /// Sets the observable with a void value - public func set() { + func set() { observable?.set() } } /// /// Observable class. Wrapper of an observable value of generic type T or an error. -/// Observable chains must be retained from the end, as an observable child retains its parent, but the parent does not retains it child (this differs from the Future). +/// Observable chains must be retained from the end, as an observable child retains its parent, but the parent does +// not retains it child (this differs from the Future). /// /// Therefore, this is a good usage of an observable: /// class MyViewController { @@ -103,7 +105,6 @@ extension ObservableResolver where T==Void { /// } /// public class Observable { - /// Observable states public enum State { case blank @@ -140,9 +141,9 @@ public class Observable { @discardableResult public func get() throws -> T { switch self { - case .value(let v): + case let .value(v): return v - case .error(let e): + case let .error(e): throw e } } @@ -151,9 +152,9 @@ public class Observable { @discardableResult public func get(error: inout Error?) -> T? { switch self { - case .value(let v): + case let .value(v): return v - case .error(let e): + case let .error(e): error = e return nil } @@ -211,7 +212,7 @@ public class Observable { do { let resolver = ObservableResolver(self) try closure(resolver) - } catch let error { + } catch { set(error) } } @@ -240,7 +241,7 @@ public class Observable { /// Sets the observable with another observable public func set(_ observable: Observable) { // Current observable retains the incoming observable - self.parent = observable + parent = observable // Incoming observable DOES NOT retain the current observable observable.resolve(success: { [weak self] value in @@ -260,7 +261,8 @@ public class Observable { }) } - /// Sets the observable with a value if not error. Either the value or the error must be provided, otherwise a crash will happen. + /// Sets the observable with a value if not error. Either the value or the error must be provided, otherwise a + // crash will happen. /// Note: error is prioritary, and if not error the value will be used. public func set(value: T?, error: Error?) { var value: T? = value @@ -302,12 +304,13 @@ public class Observable { } /// Closure called right after content is set, without waiting the then closure. - /// Note that multiple calls to this method are discouraged, resulting with only one onContentSet closure being called. + /// Note that multiple calls to this method are discouraged, resulting with only one onContentSet closure being + // called. /// Note too that if the observable has already been sent, this closure is not called. /// /// - Parameter closure: The code to be executed public func onSet(_ closure: @escaping () -> Void) { - onContentSet = { (_, _) in + onContentSet = { _, _ in closure() } } @@ -345,17 +348,15 @@ public class Observable { /// Deliver the result syncrhonously. This method might block the calling thread. /// Note that the result can only be delivered once if the observable is not reactive. public var result: Result { - get { - switch state { - case .waitingThen: - return _result! - case .blank: - semaphore = DispatchSemaphore(value: 0) - semaphore!.wait() - return self.result - case .waitingContent: - fatalError(ObservableError.thenAlreadySet.description) - } + switch state { + case .waitingThen: + return _result! + case .blank: + semaphore = DispatchSemaphore(value: 0) + semaphore!.wait() + return self.result + case .waitingContent: + fatalError(ObservableError.thenAlreadySet.description) } } @@ -366,9 +367,10 @@ public class Observable { /// - success: The then closure. /// - Returns: A chained observable @discardableResult - public func then(_ executor: Executor = MainDirectExecutor(), _ success: @escaping (T) -> Void) -> Observable { + public func then(_ executor: Executor = MainDirectExecutor(), + _ success: @escaping (T) -> Void) -> Observable { return Observable(parent: self) { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { success(value) resolver.set(value) @@ -388,9 +390,10 @@ public class Observable { /// - failure: The fail closure. /// - Returns: A chained observable @discardableResult - public func fail(_ executor: Executor = MainDirectExecutor(), _ failure: @escaping (Error) -> Void) -> Observable { + public func fail(_ executor: Executor = MainDirectExecutor(), + _ failure: @escaping (Error) -> Void) -> Observable { return Observable(parent: self) { resolver in - resolve(success: {value in + resolve(success: { value in executor.submit { resolver.set(value) } @@ -405,13 +408,13 @@ public class Observable { private func send() { switch _result! { - case .error(let error): + case let .error(error): guard let failure = failure else { print(ObservableError.missingLambda.description) return } failure(error) - case .value(let value): + case let .value(value): guard let success = success else { print(ObservableError.missingLambda.description) return @@ -419,6 +422,7 @@ public class Observable { success(value) } } + // Private lock method private func lock(_ closure: () -> Void) { lock.lock() @@ -435,9 +439,9 @@ extension Observable: CustomStringConvertible, CustomDebugStringConvertible { return "Empty observable. Waiting for value, error and then closure." case .waitingThen: switch _result! { - case .error(let error): + case let .error(error): return "Observable waiting for then closure and error set to: \(error)" - case .value(let value): + case let .value(value): return "Observable waiting for then closure and value set to: \(value)" } case .waitingContent: @@ -450,8 +454,8 @@ extension Observable: CustomStringConvertible, CustomDebugStringConvertible { } } -extension Observable where T==Void { - public func set() { - set(Void()) +public extension Observable where T == Void { + func set() { + set(()) } } diff --git a/Sources/Harmony/Future/Observable/ObservableHub.swift b/Sources/Harmony/Future/Observable/ObservableHub.swift index 7d076fb4..25b4bbe3 100644 --- a/Sources/Harmony/Future/Observable/ObservableHub.swift +++ b/Sources/Harmony/Future/Observable/ObservableHub.swift @@ -16,15 +16,14 @@ import Foundation -extension Observable { +public extension Observable { // swiftlint:disable type_name /// /// A hub acts as a cloner of a given observable. /// It can create subscribed observables, making them trigger when the main one triggers. /// - public class Hub { - + class Hub { private weak var observable: Observable? private let lock = NSLock() private var subscribers: NSHashTable> = NSHashTable.weakObjects() @@ -33,10 +32,10 @@ extension Observable { /// Note that this class will open the then closure of the observable passed on this method. /// /// - Parameter observable: The observable to be used - public init (_ observable: Observable) { + public init(_ observable: Observable) { self.observable = observable - observable.resolve(success: {value in + observable.resolve(success: { value in self.lock.lock() self.subscribers.allObjects.forEach { $0.set(value) } self.lock.unlock() @@ -58,9 +57,9 @@ extension Observable { // Sets the current value/error if exists if let result = observable?._result { switch result { - case .value(let value): + case let .value(value): subscriber.set(value) - case .error(let error): + case let .error(error): subscriber.set(error) } } diff --git a/Sources/Harmony/Security/KeychainDataSource.swift b/Sources/Harmony/Security/KeychainDataSource.swift index d4a9d8b4..199e7134 100644 --- a/Sources/Harmony/Security/KeychainDataSource.swift +++ b/Sources/Harmony/Security/KeychainDataSource.swift @@ -20,7 +20,6 @@ import Foundation // Provides a keychain service for a key value interface. // public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSource where T: Codable { - private let keychain: KeychainService public init(_ keychain: KeychainService) { @@ -46,7 +45,8 @@ public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSour return Future(CoreError.NotFound()) } guard let array = nsarray as? [T] else { - return Future(CoreError.Failed("NSArray to Array<\(String(describing: T.self))> cast failed for key \(query.key)")) + return Future(CoreError + .Failed("NSArray to Array<\(String(describing: T.self))> cast failed for key \(query.key)")) } return Future(array) default: @@ -64,8 +64,10 @@ public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSour switch keychain.set(value, forKey: query.key) { case .success: return Future(value) - case .failed(let status): - return Future(CoreError.OSStatusFailure(status, "Keychain failed to set value for key \(query.key) (OSStatus \(status))")) + case let .failed(status): + return Future(CoreError + .OSStatusFailure(status, + "Keychain failed to set value for key \(query.key) (OSStatus \(status))")) } default: query.fatalError(.put, self) @@ -81,8 +83,11 @@ public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSour switch try keychain.set(nsarray, forKey: query.key) { case .success: r.set(array) - case .failed(let status): - throw CoreError.OSStatusFailure(status, "Keychain failed to set value for key \(query.key) (OSStatus \(status))") + case let .failed(status): + throw CoreError.OSStatusFailure( + status, + "Keychain failed to set value for key \(query.key) (OSStatus \(status))" + ) } } default: @@ -96,9 +101,11 @@ public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSour case let query as KeyQuery: switch keychain.delete(query.key) { case .success: - return Future(Void()) - case .failed(let status): - return Future(CoreError.OSStatusFailure(status, "Keychain failed to delete value for key \(query.key) (OSStatus \(status))")) + return Future(()) + case let .failed(status): + return Future(CoreError + .OSStatusFailure(status, + "Keychain failed to delete value for key \(query.key) (OSStatus \(status))")) } default: query.fatalError(.delete, self) @@ -111,9 +118,11 @@ public class KeychainDataSource: GetDataSource, PutDataSource, DeleteDataSour case let query as KeyQuery: switch keychain.delete(query.key) { case .success: - return Future(Void()) - case .failed(let status): - return Future(CoreError.OSStatusFailure(status, "Keychain failed to delete value for key \(query.key) (OSStatus \(status))")) + return Future(()) + case let .failed(status): + return Future(CoreError + .OSStatusFailure(status, + "Keychain failed to delete value for key \(query.key) (OSStatus \(status))")) } default: query.fatalError(.deleteAll, self) diff --git a/Sources/Harmony/Security/KeychainGetInteractor.swift b/Sources/Harmony/Security/KeychainGetInteractor.swift index 2985ca8a..ef7dca39 100644 --- a/Sources/Harmony/Security/KeychainGetInteractor.swift +++ b/Sources/Harmony/Security/KeychainGetInteractor.swift @@ -23,7 +23,6 @@ private let defaultExecutor = DispatchQueueExecutor() /// @available(*, deprecated, message: "Use the KeychainDataSource and Repository pattern instead.") public class KeychainGetInteractor { - private let executor: Executor private let keychain: KeychainService private let key: String @@ -41,7 +40,8 @@ public class KeychainGetInteractor { } /// Convenience initializer. - /// This initializer uses a shared executor on all KeychainGetInteractor instances and the default service of Keychain(). + /// This initializer uses a shared executor on all KeychainGetInteractor instances and the default service of + // Keychain(). /// /// - Parameter key: The key to access the user defaults public convenience init(_ key: String) { diff --git a/Sources/Harmony/Security/KeychainService.swift b/Sources/Harmony/Security/KeychainService.swift index 05862a9f..d35725c0 100644 --- a/Sources/Harmony/Security/KeychainService.swift +++ b/Sources/Harmony/Security/KeychainService.swift @@ -20,18 +20,17 @@ import Security /// A user-friendly interface to store Data inside the keychain. /// public class KeychainService { - /// Arguments for the keychain queries - private struct kSec { + private enum kSec { static let classGenericPassword = NSString(format: kSecClassGenericPassword) - static let `class` = NSString(format: kSecClass) - static let attrService = NSString(format: kSecAttrService) - static let attrAccount = NSString(format: kSecAttrAccount) - static let returnAttributes = NSString(format: kSecReturnAttributes) - static let valueData = NSString(format: kSecValueData) - static let matchLimit = NSString(format: kSecMatchLimit) - static let matchLimitOne = NSString(format: kSecMatchLimitOne) - static let returnData = NSString(format: kSecReturnData) + static let `class` = NSString(format: kSecClass) + static let attrService = NSString(format: kSecAttrService) + static let attrAccount = NSString(format: kSecAttrAccount) + static let returnAttributes = NSString(format: kSecReturnAttributes) + static let valueData = NSString(format: kSecValueData) + static let matchLimit = NSString(format: kSecMatchLimit) + static let matchLimitOne = NSString(format: kSecMatchLimitOne) + static let returnData = NSString(format: kSecReturnData) } /// The Keychain's service name. @@ -59,8 +58,10 @@ public class KeychainService { /// - Parameter key: The key. /// - Returns: The stored Data or nil. public func get(_ key: String) -> Data? { - let query = NSDictionary(objects: [kSec.classGenericPassword, service, key, kCFBooleanTrue!, kSec.matchLimitOne], - forKeys: [kSec.class, kSec.attrService, kSec.attrAccount, kSec.returnData, kSec.matchLimit]) + let query = NSDictionary( + objects: [kSec.classGenericPassword, service, key, kCFBooleanTrue!, kSec.matchLimitOne], + forKeys: [kSec.class, kSec.attrService, kSec.attrAccount, kSec.returnData, kSec.matchLimit] + ) var dataRef: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &dataRef) @@ -81,7 +82,12 @@ public class KeychainService { @discardableResult public func set(_ data: Data, forKey key: String) -> Result { let query = NSMutableDictionary(objects: [kSec.classGenericPassword, service, key, kCFBooleanTrue!], - forKeys: [kSec.class, kSec.attrService, kSec.attrAccount, kSec.returnAttributes]) + forKeys: [ + kSec.class, + kSec.attrService, + kSec.attrAccount, + kSec.returnAttributes, + ]) // Delete first and old entry let deleteStatus = SecItemDelete(query as CFDictionary) if deleteStatus != errSecSuccess { @@ -105,7 +111,12 @@ public class KeychainService { @discardableResult public func delete(_ key: String) -> Result { let query = NSMutableDictionary(objects: [kSec.classGenericPassword, service, key, kCFBooleanTrue!], - forKeys: [kSec.class, kSec.attrService, kSec.attrAccount, kSec.returnAttributes]) + forKeys: [ + kSec.class, + kSec.attrService, + kSec.attrAccount, + kSec.returnAttributes, + ]) // Delete first and old entry let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess { @@ -117,7 +128,6 @@ public class KeychainService { } public extension KeychainService { - /// Custom getter for Decodable conforming types. /// /// - Parameter key: The key. diff --git a/Sources/Harmony/Security/KeychainSetInteractor.swift b/Sources/Harmony/Security/KeychainSetInteractor.swift index 14f3fe04..7b214d36 100644 --- a/Sources/Harmony/Security/KeychainSetInteractor.swift +++ b/Sources/Harmony/Security/KeychainSetInteractor.swift @@ -23,7 +23,6 @@ private let defaultExecutor = DispatchQueueExecutor() /// @available(*, deprecated, message: "Use the KeychainDataSource and Repository pattern instead.") public class KeychainSetInteractor { - private let executor: Executor private let keychain: KeychainService private let key: String @@ -41,7 +40,8 @@ public class KeychainSetInteractor { } /// Convenience initializer. - /// This initializer uses a shared executor on all KeychainSetInteractor instances and the default service of Keychain(). + /// This initializer uses a shared executor on all KeychainSetInteractor instances and the default service of + // Keychain(). /// /// - Parameter key: The key to access the user defaults public convenience init(_ key: String) { @@ -57,8 +57,11 @@ public class KeychainSetInteractor { switch result { case .success: resolver.set(true) - case .failed(let status): - resolver.set(CoreError.OSStatusFailure(status, "Keychain failed to set value for key \(self.key) (OSStatus \(status))")) + case let .failed(status): + resolver + .set(CoreError + .OSStatusFailure(status, + "Keychain failed to set value for key \(self.key) (OSStatus \(status))")) } } } diff --git a/Sources/Harmony/Security/SecureKey.swift b/Sources/Harmony/Security/SecureKey.swift index a5c84798..5790a34b 100644 --- a/Sources/Harmony/Security/SecureKey.swift +++ b/Sources/Harmony/Security/SecureKey.swift @@ -21,17 +21,16 @@ import Security /// Stores securely inside the Keychain an auto-generated data blob (aka. Key). /// public class SecureKey { - /// Arguments for the keychain queries - private struct kSec { - static let `class` = NSString(format: kSecClass) - static let classKey = NSString(format: kSecClassKey) - static let attrApplicationTag = NSString(format: kSecAttrApplicationTag) - static let attrKeySizeInBits = NSString(format: kSecAttrKeySizeInBits) - static let returnData = NSString(format: kSecReturnData) - static let attrAccessible = NSString(format: kSecAttrAccessible) + private enum kSec { + static let `class` = NSString(format: kSecClass) + static let classKey = NSString(format: kSecClassKey) + static let attrApplicationTag = NSString(format: kSecAttrApplicationTag) + static let attrKeySizeInBits = NSString(format: kSecAttrKeySizeInBits) + static let returnData = NSString(format: kSecReturnData) + static let attrAccessible = NSString(format: kSecAttrAccessible) static let attrAccessibleAlways = NSString(format: kSecAttrAccessibleAfterFirstUnlock) - static let valueData = NSString(format: kSecValueData) + static let valueData = NSString(format: kSecValueData) } /// The key identifier @@ -101,7 +100,12 @@ public class SecureKey { throw CoreError.Failed("Failed to convert the SecureKey identifier to data") } let query = NSDictionary(objects: [kSec.classKey, tag, length, true], - forKeys: [kSec.class, kSec.attrApplicationTag, kSec.attrKeySizeInBits, kSec.returnData]) + forKeys: [ + kSec.class, + kSec.attrApplicationTag, + kSec.attrKeySizeInBits, + kSec.returnData, + ]) var dataRef: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &dataRef) switch status { @@ -111,7 +115,10 @@ public class SecureKey { case -25308: // errKCInteractionNotAllowed // If reading fails because app is not allowed (device locked) // Fix cannot be applied because we cannot read the current keychain item. - throw CoreError.OSStatusFailure(status, "Failed to fetch Keychain because the device is locked (OSStatus: \(status)).") + throw CoreError.OSStatusFailure( + status, + "Failed to fetch Keychain because the device is locked (OSStatus: \(status))." + ) default: // If no pre-existing key from this application @@ -120,7 +127,13 @@ public class SecureKey { } let query = NSDictionary(objects: [kSec.classKey, tag, length, kSec.attrAccessibleAlways, keyData], - forKeys: [kSec.class, kSec.attrApplicationTag, kSec.attrKeySizeInBits, kSec.attrAccessible, kSec.valueData]) + forKeys: [ + kSec.class, + kSec.attrApplicationTag, + kSec.attrKeySizeInBits, + kSec.attrAccessible, + kSec.valueData, + ]) let status = SecItemAdd(query as CFDictionary, nil) guard status == errSecSuccess else { throw CoreError.OSStatusFailure(status, "Failed to insert key data with OSStatus: \(status)") diff --git a/Sources/HarmonyTesting/Data/DataSourceSpy.swift b/Sources/HarmonyTesting/Data/DataSourceSpy.swift index e40700c9..21a26d44 100644 --- a/Sources/HarmonyTesting/Data/DataSourceSpy.swift +++ b/Sources/HarmonyTesting/Data/DataSourceSpy.swift @@ -18,8 +18,7 @@ import Foundation import Harmony /// A GetDataSource spy that records all calls. -public class GetDataSourceSpy : GetDataSource where D.T == T { - +public class GetDataSourceSpy: GetDataSource where D.T == T { public private(set) var getCalls: [Query] = [] public private(set) var getAllCalls: [Query] = [] @@ -41,8 +40,7 @@ public class GetDataSourceSpy : GetDataSource where D.T == } /// A PutDataSource spy that records all calls. -public class PutDataSourceSpy : PutDataSource where D.T == T { - +public class PutDataSourceSpy: PutDataSource where D.T == T { public private(set) var putCalls: [(value: T?, query: Query)] = [] public private(set) var putAllCalls: [(array: [T], query: Query)] = [] @@ -64,8 +62,7 @@ public class PutDataSourceSpy : PutDataSource where D.T == } /// A DeleteDataSource spy that records all calls. -public class DeleteDataSourceSpy : DeleteDataSource { - +public class DeleteDataSourceSpy: DeleteDataSource { public private(set) var deleteCalls: [Query] = [] public private(set) var deleteAllCalls: [Query] = [] @@ -87,8 +84,8 @@ public class DeleteDataSourceSpy : DeleteDataSource { } /// A DataSource spy that records all calls. -public class DataSourceSpy : GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, D: PutDataSource, D: DeleteDataSource, D.T == T { - +public class DataSourceSpy: GetDataSource, PutDataSource, DeleteDataSource where D: GetDataSource, + D: PutDataSource, D: DeleteDataSource, D.T == T { public private(set) var getCalls: [Query] = [] public private(set) var getAllCalls: [Query] = [] diff --git a/Sources/HarmonyTesting/Data/MockObjectValidation.swift b/Sources/HarmonyTesting/Data/MockObjectValidation.swift index 20ef369e..3dab276c 100644 --- a/Sources/HarmonyTesting/Data/MockObjectValidation.swift +++ b/Sources/HarmonyTesting/Data/MockObjectValidation.swift @@ -22,11 +22,11 @@ public struct MockObjectValidation: ObjectValidation { self.arrayValid = arrayValid } - public func isObjectValid(_ object: T) -> Bool { + public func isObjectValid(_: T) -> Bool { return objectValid } - public func isArrayValid(_ objects: [T]) -> Bool { + public func isArrayValid(_: [T]) -> Bool { return arrayValid } } diff --git a/Sources/HarmonyTesting/Data/RepositorySpy.swift b/Sources/HarmonyTesting/Data/RepositorySpy.swift index a61dcc33..4a76cc65 100644 --- a/Sources/HarmonyTesting/Data/RepositorySpy.swift +++ b/Sources/HarmonyTesting/Data/RepositorySpy.swift @@ -18,7 +18,7 @@ import Foundation import Harmony /// A GetRepository spy that records all calls. -public class GetRepositorySpy : GetRepository where D.T == T { +public class GetRepositorySpy: GetRepository where D.T == T { // swiftlint:disable large_tuple public private(set) var getCalls: [(query: Query, operation: Harmony.Operation)] = [] @@ -27,7 +27,7 @@ public class GetRepositorySpy : GetRepository where D.T == private let repository: D public init(_ dataSource: D) { - self.repository = dataSource + repository = dataSource } public func get(_ query: Query, operation: Harmony.Operation) -> Future { @@ -42,15 +42,14 @@ public class GetRepositorySpy : GetRepository where D.T == } /// A PutRepository spy that records all calls. -public class PutRepositorySpy : PutRepository where D.T == T { - +public class PutRepositorySpy: PutRepository where D.T == T { public private(set) var putCalls: [(value: T?, query: Query, operation: Harmony.Operation)] = [] public private(set) var putAllCalls: [(array: [T], query: Query, operation: Harmony.Operation)] = [] private let repository: D public init(_ dataSource: D) { - self.repository = dataSource + repository = dataSource } public func put(_ value: T?, in query: Query, operation: Harmony.Operation) -> Future { @@ -65,15 +64,14 @@ public class PutRepositorySpy : PutRepository where D.T == } /// A DeleteRepository spy that records all calls. -public class DeleteRepositorySpy : DeleteRepository { - +public class DeleteRepositorySpy: DeleteRepository { public private(set) var deleteCalls: [(query: Query, operation: Harmony.Operation)] = [] public private(set) var deleteAllCalls: [(query: Query, operation: Harmony.Operation)] = [] private let repository: D public init(_ dataSource: D) { - self.repository = dataSource + repository = dataSource } public func delete(_ query: Query, operation: Harmony.Operation) -> Future { @@ -88,15 +86,15 @@ public class DeleteRepositorySpy : DeleteRepository { } /// A Repository spy that records all calls. -public class RepositorySpy : GetRepository, PutRepository, DeleteRepository where D: GetRepository, D: PutRepository, D: DeleteRepository, D.T == T { - +public class RepositorySpy: GetRepository, PutRepository, DeleteRepository where D: GetRepository, + D: PutRepository, D: DeleteRepository, D.T == T { public private(set) var getCalls: [(query: Query, operation: Harmony.Operation)] = [] public private(set) var getAllCalls: [(query: Query, operation: Harmony.Operation)] = [] private let repository: D public init(_ dataSource: D) { - self.repository = dataSource + repository = dataSource } public func get(_ query: Query, operation: Harmony.Operation) -> Future { diff --git a/Sources/HarmonyTesting/Interactor/MockInteractorDelete.swift b/Sources/HarmonyTesting/Interactor/MockInteractorDelete.swift index beadb87b..b19cd74a 100644 --- a/Sources/HarmonyTesting/Interactor/MockInteractorDelete.swift +++ b/Sources/HarmonyTesting/Interactor/MockInteractorDelete.swift @@ -23,10 +23,13 @@ public extension Interactor { public required init(expectedResult: Result) { self.expectedResult = expectedResult - super.init(DirectExecutor(), SingleDataSourceRepository, Any>(InMemoryDataSource())) + super.init( + DirectExecutor(), + SingleDataSourceRepository, Any>(InMemoryDataSource()) + ) } - public required init(_ executor: Executor, _ repository: DeleteRepository) { + public required init(_: Executor, _: DeleteRepository) { fatalError("init(_:_:) has not been implemented") } @@ -37,15 +40,18 @@ public extension Interactor { } @discardableResult - override public func execute(_ query: Query, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) - self.spyQuery.append(query) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ query: Query, + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future { + spyOperation.append(operation) + spyQuery.append(query) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -53,15 +59,15 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { - - self.spyOperation.append(operation) - self.spyId.append(id) + override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future where K: Hashable { + spyOperation.append(operation) + spyId.append(id) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -71,12 +77,15 @@ public extension Interactor { private let expectedResult: Result public required init(expectedResult: Result) { - self.expectedResult = expectedResult - super.init(DirectExecutor(), SingleDataSourceRepository, Any>(InMemoryDataSource()), VoidQuery()) + super.init( + DirectExecutor(), + SingleDataSourceRepository, Any>(InMemoryDataSource()), + VoidQuery() + ) } - public required init(_ executor: Executor, _ repository: DeleteRepository, _ query: Query) { + public required init(_: Executor, _: DeleteRepository, _: Query) { fatalError("init(_:_:_:) has not been implemented") } @@ -86,14 +95,14 @@ public extension Interactor { } @discardableResult - override public func execute(_ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) + override public func execute(_ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future { + spyOperation.append(operation) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -103,12 +112,14 @@ public extension Interactor { private let expectedResult: Result public required init(expectedResult: Result) { - self.expectedResult = expectedResult - super.init(DirectExecutor(), SingleDataSourceRepository, Any>(InMemoryDataSource())) + super.init( + DirectExecutor(), + SingleDataSourceRepository, Any>(InMemoryDataSource()) + ) } - public required init(_ executor: Executor, _ repository: DeleteRepository) { + public required init(_: Executor, _: DeleteRepository) { fatalError("init(_:_:) has not been implemented") } @@ -119,15 +130,18 @@ public extension Interactor { } @discardableResult - override public func execute(_ query: Query, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) - self.spyQuery.append(query) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ query: Query, + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future { + spyOperation.append(operation) + spyQuery.append(query) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -135,15 +149,15 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { - - self.spyOperation.append(operation) - self.spyId.append(id) + override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future where K: Hashable { + spyOperation.append(operation) + spyId.append(id) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -153,12 +167,15 @@ public extension Interactor { private let expectedResult: Result public required init(expectedResult: Result) { - self.expectedResult = expectedResult - super.init(DirectExecutor(), SingleDataSourceRepository, Any>(InMemoryDataSource()), VoidQuery()) + super.init( + DirectExecutor(), + SingleDataSourceRepository, Any>(InMemoryDataSource()), + VoidQuery() + ) } - public required init(_ executor: Executor, _ repository: DeleteRepository, _ query: Query) { + public required init(_: Executor, _: DeleteRepository, _: Query) { fatalError("init(_:_:_:) has not been implemented") } @@ -168,14 +185,14 @@ public extension Interactor { } @discardableResult - override public func execute(_ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) + override public func execute(_ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future { + spyOperation.append(operation) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } diff --git a/Sources/HarmonyTesting/Interactor/MockInteractorGet.swift b/Sources/HarmonyTesting/Interactor/MockInteractorGet.swift index 9bf50ebc..cd97aee5 100644 --- a/Sources/HarmonyTesting/Interactor/MockInteractorGet.swift +++ b/Sources/HarmonyTesting/Interactor/MockInteractorGet.swift @@ -26,7 +26,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource())) } - public required init(_ executor: Executor, _ repository: R) where T == R.T, R: GetRepository { + public required init(_: Executor, _: R) where T == R.T, R: GetRepository { fatalError("init(_:_:) has not been implemented") } @@ -37,15 +37,18 @@ public extension Interactor { } @discardableResult - override public func execute(_ query: Query = VoidQuery(), _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) - self.spyQuery.append(query) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ query: Query = VoidQuery(), + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future { + spyOperation.append(operation) + spyQuery.append(query) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -53,15 +56,15 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { + override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future where K: Hashable { + spyOperation.append(operation) + spyId.append(id) - self.spyOperation.append(operation) - self.spyId.append(id) - - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -75,7 +78,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource()), VoidQuery()) } - public required init(_ executor: Executor, _ repository: R, _ query: Query) where T == R.T, R: GetRepository { + public required init(_: Executor, _: R, _: Query) where T == R.T, R: GetRepository { fatalError("init(_:_:_:) has not been implemented") } @@ -85,14 +88,14 @@ public extension Interactor { } @discardableResult - override public func execute(_ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyOperation.append(operation) + override public func execute(_ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future { + spyOperation.append(operation) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -106,7 +109,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource())) } - public required init(_ executor: Executor, _ repository: R) where T == R.T, R: GetRepository { + public required init(_: Executor, _: R) where T == R.T, R: GetRepository { fatalError("init(_:_:) has not been implemented") } @@ -117,15 +120,18 @@ public extension Interactor { } @discardableResult - override public func execute(_ query: Query = AllObjectsQuery(), _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { - - self.spyOperation.append(operation) - self.spyQuery.append(query) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ query: Query = AllObjectsQuery(), + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future<[T]> { + spyOperation.append(operation) + spyQuery.append(query) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -133,15 +139,15 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> where K: Hashable { + override public func execute(_ id: K, _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future<[T]> where K: Hashable { + spyOperation.append(operation) + spyId.append(id) - self.spyOperation.append(operation) - self.spyId.append(id) - - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -155,7 +161,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource()), VoidQuery()) } - public required init(_ executor: Executor, _ repository: R, _ query: Query) where T == R.T, R: GetRepository { + public required init(_: Executor, _: R, _: Query) where T == R.T, R: GetRepository { fatalError("init(_:_:_:) has not been implemented") } @@ -165,14 +171,14 @@ public extension Interactor { } @discardableResult - override public func execute(_ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { - - self.spyOperation.append(operation) + override public func execute(_ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future<[T]> { + spyOperation.append(operation) - switch self.expectedResult { - case .success(let value): + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } diff --git a/Sources/HarmonyTesting/Interactor/MockInteractorPut.swift b/Sources/HarmonyTesting/Interactor/MockInteractorPut.swift index 27db2c0b..3daad665 100644 --- a/Sources/HarmonyTesting/Interactor/MockInteractorPut.swift +++ b/Sources/HarmonyTesting/Interactor/MockInteractorPut.swift @@ -26,7 +26,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource())) } - public required init(_ executor: Executor, _ repository: R) where T == R.T, R: PutRepository { + public required init(_: Executor, _: R) where T == R.T, R: PutRepository { fatalError("init(_:_:) has not been implemented") } @@ -39,16 +39,20 @@ public extension Interactor { public var spyOperation: [Harmony.Operation] = [] @discardableResult - override public func execute(_ value: T? = nil, query: Query = VoidQuery(), _ operation: Harmony.Operation = DefaultOperation(), in executor: Harmony.Executor? = nil) -> Future { - - self.spyExecuteValue.append(value) - self.spyQuery.append(query) - self.spyOperation.append(operation) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ value: T? = nil, + query: Query = VoidQuery(), + _ operation: Harmony.Operation = DefaultOperation(), + in _: Harmony.Executor? = nil + ) -> Future { + spyExecuteValue.append(value) + spyQuery.append(query) + spyOperation.append(operation) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -56,16 +60,18 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ value: T?, forId id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future where K: Hashable { - - self.spyExecuteValue.append(value) - self.spyId.append(id) - self.spyOperation.append(operation) - - switch self.expectedResult { - case .success(let value): + override public func execute(_ value: T?, forId id: K, + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future + where K: Hashable { + spyExecuteValue.append(value) + spyId.append(id) + spyOperation.append(operation) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -79,7 +85,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource()), VoidQuery()) } - public required init(_ executor: Executor, _ repository: R, _ query: Query) where T == R.T, R: PutRepository { + public required init(_: Executor, _: R, _: Query) where T == R.T, R: PutRepository { fatalError("init(_:_:_:) has not been implemented") } @@ -91,15 +97,18 @@ public extension Interactor { public var spyOperation: [Harmony.Operation] = [] @discardableResult - override public func execute(_ value: T? = nil, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future { - - self.spyExecuteValue.append(value) - self.spyOperation.append(operation) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ value: T? = nil, + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future { + spyExecuteValue.append(value) + spyOperation.append(operation) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -113,7 +122,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource())) } - public required init(_ executor: Executor, _ repository: R) where T == R.T, R: PutRepository { + public required init(_: Executor, _: R) where T == R.T, R: PutRepository { fatalError("init(_:_:) has not been implemented") } @@ -126,16 +135,20 @@ public extension Interactor { public var spyOperation: [Harmony.Operation] = [] @discardableResult - override public func execute(_ array: [T] = [], query: Query = VoidQuery(), _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { - - self.spyExecuteValue.append(array) - self.spyQuery.append(query) - self.spyOperation.append(operation) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ array: [T] = [], + query: Query = VoidQuery(), + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future<[T]> { + spyExecuteValue.append(array) + spyQuery.append(query) + spyOperation.append(operation) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -143,16 +156,18 @@ public extension Interactor { public var spyId: [Any] = [] @discardableResult - override public func execute(_ array: [T] = [], forId id: K, _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> where K: Hashable { - - self.spyExecuteValue.append(array) - self.spyOperation.append(operation) - self.spyId.append(id) - - switch self.expectedResult { - case .success(let value): + override public func execute(_ array: [T] = [], forId id: K, + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil) -> Future<[T]> + where K: Hashable { + spyExecuteValue.append(array) + spyOperation.append(operation) + spyId.append(id) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } @@ -166,7 +181,7 @@ public extension Interactor { super.init(DirectExecutor(), SingleDataSourceRepository(InMemoryDataSource()), VoidQuery()) } - public required init(_ executor: Executor, _ repository: R, _ query: Query) where T == R.T, R: PutRepository { + public required init(_: Executor, _: R, _: Query) where T == R.T, R: PutRepository { fatalError("init(_:_:_:) has not been implemented") } @@ -178,15 +193,18 @@ public extension Interactor { public var spyOperation: [Harmony.Operation] = [] @discardableResult - override public func execute(_ array: [T] = [], _ operation: Harmony.Operation = DefaultOperation(), in executor: Executor? = nil) -> Future<[T]> { - - self.spyExecuteValue.append(array) - self.spyOperation.append(operation) - - switch self.expectedResult { - case .success(let value): + override public func execute( + _ array: [T] = [], + _ operation: Harmony.Operation = DefaultOperation(), + in _: Executor? = nil + ) -> Future<[T]> { + spyExecuteValue.append(array) + spyOperation.append(operation) + + switch expectedResult { + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } diff --git a/Sources/HarmonyTesting/ObjectMother/BoolObjectMother.swift b/Sources/HarmonyTesting/ObjectMother/BoolObjectMother.swift index ea0db43f..54007fc5 100644 --- a/Sources/HarmonyTesting/ObjectMother/BoolObjectMother.swift +++ b/Sources/HarmonyTesting/ObjectMother/BoolObjectMother.swift @@ -17,5 +17,5 @@ import Foundation public func randomBool() -> Bool { - return Int.random(in: 0...1) != 0 + return Int.random(in: 0 ... 1) != 0 } diff --git a/Sources/HarmonyTesting/ObjectMother/DoubleObjectMother.swift b/Sources/HarmonyTesting/ObjectMother/DoubleObjectMother.swift index b7e62cfb..c7861707 100644 --- a/Sources/HarmonyTesting/ObjectMother/DoubleObjectMother.swift +++ b/Sources/HarmonyTesting/ObjectMother/DoubleObjectMother.swift @@ -17,5 +17,5 @@ import Foundation public func anyDouble(minValue: Double = -32000, maxValue: Double = 32000) -> Double { - return Double.random(in: minValue...maxValue) + return Double.random(in: minValue ... maxValue) } diff --git a/Sources/HarmonyTesting/ObjectMother/IntegerObjectModel.swift b/Sources/HarmonyTesting/ObjectMother/IntegerObjectModel.swift index c837a83f..aed0d2fb 100644 --- a/Sources/HarmonyTesting/ObjectMother/IntegerObjectModel.swift +++ b/Sources/HarmonyTesting/ObjectMother/IntegerObjectModel.swift @@ -17,5 +17,5 @@ import Foundation public func anyInt(minValue: Int = -32000, maxValue: Int = 32000) -> Int { - return Int.random(in: minValue...maxValue) + return Int.random(in: minValue ... maxValue) } diff --git a/Sources/HarmonyTesting/TestUtils.swift b/Sources/HarmonyTesting/TestUtils.swift index 197b2494..3137c17a 100644 --- a/Sources/HarmonyTesting/TestUtils.swift +++ b/Sources/HarmonyTesting/TestUtils.swift @@ -19,9 +19,9 @@ import Harmony public enum TestUtils { public static func result(expectedResult: Result) -> Future { switch expectedResult { - case .success(let value): + case let .success(value): return Future(value) - case .failure(let error): + case let .failure(error): return Future(error) } } diff --git a/Tests/HarmonyTests/CacheRepositoryTests.swift b/Tests/HarmonyTests/CacheRepositoryTests.swift index 797d468e..01c9484a 100644 --- a/Tests/HarmonyTests/CacheRepositoryTests.swift +++ b/Tests/HarmonyTests/CacheRepositoryTests.swift @@ -15,13 +15,12 @@ // import Foundation -import Nimble -import XCTest import Harmony import HarmonyTesting +import Nimble +import XCTest class CacheRepositoryTests: XCTestCase { - private var main: InMemoryDataSource! private var cache: InMemoryDataSource! diff --git a/Tests/HarmonyTests/DelayedMainQueueExecutorTests.swift b/Tests/HarmonyTests/DelayedMainQueueExecutorTests.swift index 245a2afe..fb446e40 100644 --- a/Tests/HarmonyTests/DelayedMainQueueExecutorTests.swift +++ b/Tests/HarmonyTests/DelayedMainQueueExecutorTests.swift @@ -5,12 +5,11 @@ // Created by Borja Arias Drake on 21.09.2022.. // -import XCTest -import Nimble import Harmony +import Nimble +import XCTest final class DelayedMainQueueExecutorTests: XCTestCase { - func test_submit() throws { // Given let executor = DelayedMainQueueExecutor() diff --git a/Tests/HarmonyTests/DeviceStorageDataSourcePrefixTests.swift b/Tests/HarmonyTests/DeviceStorageDataSourcePrefixTests.swift index bba0482f..479d8425 100644 --- a/Tests/HarmonyTests/DeviceStorageDataSourcePrefixTests.swift +++ b/Tests/HarmonyTests/DeviceStorageDataSourcePrefixTests.swift @@ -9,8 +9,10 @@ import Foundation import XCTest class DeviceStorageDataSourcePrefixTests: XCTestCase { - - private let tester = DeviceStorageDataSourceTester(DeviceStorageDataSourceObjectMother(deviceStorageType: .prefix("test-prefix"))) + private let tester = + DeviceStorageDataSourceTester( + DeviceStorageDataSourceObjectMother(deviceStorageType: .prefix("test-prefix")) + ) override func tearDown() { tester.tearDown() @@ -83,5 +85,4 @@ class DeviceStorageDataSourcePrefixTests: XCTestCase { func test_should_replace_previous_value_when_inserting_with_existing_key() throws { try tester.test_should_replace_previous_value_when_inserting_with_existing_key() } - } diff --git a/Tests/HarmonyTests/DeviceStorageDataSourceRegularTests.swift b/Tests/HarmonyTests/DeviceStorageDataSourceRegularTests.swift index ca244dae..168f6b98 100644 --- a/Tests/HarmonyTests/DeviceStorageDataSourceRegularTests.swift +++ b/Tests/HarmonyTests/DeviceStorageDataSourceRegularTests.swift @@ -9,8 +9,8 @@ import Foundation import XCTest class DeviceStorageDataSourceRegularTests: XCTestCase { - - private let tester = DeviceStorageDataSourceTester(DeviceStorageDataSourceObjectMother(deviceStorageType: .regular)) + private let tester = + DeviceStorageDataSourceTester(DeviceStorageDataSourceObjectMother(deviceStorageType: .regular)) override func tearDown() { tester.tearDown() @@ -51,7 +51,6 @@ class DeviceStorageDataSourceRegularTests: XCTestCase { func test_delete_all_values() throws { // TODO: decide what to do with deleteAll implementation when deviceStorageType is regular // try tester.test_delete_all_values() - } func test_get_value_not_found() throws { @@ -85,5 +84,4 @@ class DeviceStorageDataSourceRegularTests: XCTestCase { func test_should_replace_previous_value_when_inserting_with_existing_key() throws { try tester.test_should_replace_previous_value_when_inserting_with_existing_key() } - } diff --git a/Tests/HarmonyTests/DeviceStorageDataSourceRootKeyTests.swift b/Tests/HarmonyTests/DeviceStorageDataSourceRootKeyTests.swift index 9b9dc826..d7a01b4b 100644 --- a/Tests/HarmonyTests/DeviceStorageDataSourceRootKeyTests.swift +++ b/Tests/HarmonyTests/DeviceStorageDataSourceRootKeyTests.swift @@ -9,8 +9,10 @@ import Foundation import XCTest class DeviceStorageDataSourceRootKeyTests: XCTestCase { - - private let tester = DeviceStorageDataSourceTester(DeviceStorageDataSourceObjectMother(deviceStorageType: .rootKey("test-root-key"))) + private let tester = + DeviceStorageDataSourceTester( + DeviceStorageDataSourceObjectMother(deviceStorageType: .rootKey("test-root-key")) + ) override func tearDown() { tester.tearDown() @@ -83,5 +85,4 @@ class DeviceStorageDataSourceRootKeyTests: XCTestCase { func test_should_replace_previous_value_when_inserting_with_existing_key() throws { try tester.test_should_replace_previous_value_when_inserting_with_existing_key() } - } diff --git a/Tests/HarmonyTests/DeviceStorageDataSourceTester.swift b/Tests/HarmonyTests/DeviceStorageDataSourceTester.swift index c16ae193..f04b80a4 100644 --- a/Tests/HarmonyTests/DeviceStorageDataSourceTester.swift +++ b/Tests/HarmonyTests/DeviceStorageDataSourceTester.swift @@ -6,14 +6,18 @@ // import Foundation +import Harmony import Nimble import XCTest -import Harmony struct DeviceStorageDataSourceObjectMother { let deviceStorageType: DeviceStorageType - func provideDataSource(userDefaults: UserDefaults, insertValue: (IdQuery, T)? = nil, insertValues: (IdQuery, [T])? = nil) throws -> DeviceStorageDataSource { + func provideDataSource( + userDefaults: UserDefaults, + insertValue: (IdQuery, T)? = nil, + insertValues: (IdQuery, [T])? = nil + ) throws -> DeviceStorageDataSource { let dataSource = DeviceStorageDataSource(userDefaults, storageType: deviceStorageType) if let insertValue = insertValue { @@ -29,7 +33,6 @@ struct DeviceStorageDataSourceObjectMother { } class DeviceStorageDataSourceTester { - let dataSourceObjectMother: DeviceStorageDataSourceObjectMother init(_ dataSourceObjectMother: DeviceStorageDataSourceObjectMother) { @@ -38,8 +41,15 @@ class DeviceStorageDataSourceTester { let userDefaults = UserDefaults.standard - private func provideDataSource(insertValue: (IdQuery, T)? = nil, insertValues: (IdQuery, [T])? = nil) throws -> DeviceStorageDataSource { - return try dataSourceObjectMother.provideDataSource(userDefaults: userDefaults, insertValue: insertValue, insertValues: insertValues) + private func provideDataSource( + insertValue: (IdQuery, T)? = nil, + insertValues: (IdQuery, [T])? = nil + ) throws -> DeviceStorageDataSource { + return try dataSourceObjectMother.provideDataSource( + userDefaults: userDefaults, + insertValue: insertValue, + insertValues: insertValues + ) } func tearDown() { @@ -172,7 +182,10 @@ class DeviceStorageDataSourceTester { let valueQuery = IdQuery(String(randomOfLength: 8)) let values = [Int.random(), Int.random()] let valuesQuery = IdQuery(String(randomOfLength: 8)) - let dataSource = try provideDataSource(insertValue: (valueQuery, value), insertValues: (valuesQuery, values)) + let dataSource = try provideDataSource( + insertValue: (valueQuery, value), + insertValues: (valuesQuery, values) + ) // When try dataSource.delete(AllObjectsQuery()).result.get() @@ -305,5 +318,4 @@ class DeviceStorageDataSourceTester { // Then .to(throwError(errorType: CoreError.NotFound.self)) // The old value (list) is not there anymore } - } diff --git a/Tests/HarmonyTests/FileSystemStorageDataSourceTests.swift b/Tests/HarmonyTests/FileSystemStorageDataSourceTests.swift index f36e9c78..21b5050d 100644 --- a/Tests/HarmonyTests/FileSystemStorageDataSourceTests.swift +++ b/Tests/HarmonyTests/FileSystemStorageDataSourceTests.swift @@ -6,12 +6,15 @@ // import Foundation +import Harmony import Nimble import XCTest -import Harmony class FileSystemStorageDataSourceTests: XCTestCase { - private func provideDataSource(insertValue: (IdQuery, Data)? = nil, insertValues: (IdQuery, [Data])? = nil) throws -> FileSystemStorageDataSource { + private func provideDataSource( + insertValue: (IdQuery, Data)? = nil, + insertValues: (IdQuery, [Data])? = nil + ) throws -> FileSystemStorageDataSource { let dataSource = FileSystemStorageDataSource(fileManager: FileManager.default, relativePath: "test")! if let insertValue = insertValue { @@ -49,7 +52,10 @@ class FileSystemStorageDataSourceTests: XCTestCase { func test_getAll_value() throws { // Given let query = IdQuery(String(randomOfLength: 8)) - let expectedValue = [String(randomOfLength: 8).data(using: .utf8)!, String(randomOfLength: 8).data(using: .utf8)!] + let expectedValue = [ + String(randomOfLength: 8).data(using: .utf8)!, + String(randomOfLength: 8).data(using: .utf8)!, + ] let dataSource = try provideDataSource(insertValues: (query, expectedValue)) // When @@ -77,7 +83,10 @@ class FileSystemStorageDataSourceTests: XCTestCase { func test_putAll_value() throws { // Given let query = IdQuery(String(randomOfLength: 8)) - let expectedValue = [String(randomOfLength: 8).data(using: .utf8)!, String(randomOfLength: 8).data(using: .utf8)!] + let expectedValue = [ + String(randomOfLength: 8).data(using: .utf8)!, + String(randomOfLength: 8).data(using: .utf8)!, + ] let dataSource = try provideDataSource() // When @@ -111,7 +120,10 @@ class FileSystemStorageDataSourceTests: XCTestCase { let valueQuery = IdQuery(String(randomOfLength: 8)) let values = [String(randomOfLength: 8).data(using: .utf8)!, String(randomOfLength: 8).data(using: .utf8)!] let valuesQuery = IdQuery(String(randomOfLength: 8)) - let dataSource = try provideDataSource(insertValue: (valueQuery, value), insertValues: (valuesQuery, values)) + let dataSource = try provideDataSource( + insertValue: (valueQuery, value), + insertValues: (valuesQuery, values) + ) // When try dataSource.delete(AllObjectsQuery()).result.get() @@ -225,7 +237,10 @@ class FileSystemStorageDataSourceTests: XCTestCase { func test_should_replace_previous_value_when_inserting_with_existing_key() throws { // Given let query = IdQuery(String(randomOfLength: 8)) - let firstValue = [String(randomOfLength: 8).data(using: .utf8)!, String(randomOfLength: 8).data(using: .utf8)!] + let firstValue = [ + String(randomOfLength: 8).data(using: .utf8)!, + String(randomOfLength: 8).data(using: .utf8)!, + ] let secondValue = String(randomOfLength: 8).data(using: .utf8)! let dataSource = try provideDataSource(insertValues: (query, firstValue)) @@ -244,5 +259,4 @@ class FileSystemStorageDataSourceTests: XCTestCase { // Then .to(throwError(errorType: CoreError.NotFound.self)) // The old value (list) is not there anymore } - } diff --git a/Tests/HarmonyTests/FutureTests.swift b/Tests/HarmonyTests/FutureTests.swift index 6cd34054..58ec937a 100644 --- a/Tests/HarmonyTests/FutureTests.swift +++ b/Tests/HarmonyTests/FutureTests.swift @@ -5,13 +5,12 @@ // Created by Joan Martin on 16/6/22. // -import XCTest import Harmony import HarmonyTesting import Nimble +import XCTest class FutureTests: XCTestCase { - override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } @@ -23,7 +22,7 @@ class FutureTests: XCTestCase { // Success Errors func test_future_value_set_on_init() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) // When let future = Future(anyValue) @@ -34,7 +33,7 @@ class FutureTests: XCTestCase { func test_future_value_set_on_set_value() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let future = Future() // When @@ -46,7 +45,7 @@ class FutureTests: XCTestCase { func test_future_value_set_on_set_value_or_error() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let future = Future() // When @@ -93,7 +92,7 @@ class FutureTests: XCTestCase { func test_future_states_on_value_first_then_after() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let future = Future() // When @@ -113,7 +112,7 @@ class FutureTests: XCTestCase { func test_future_states_on_then_first_value_after() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let future = Future() // When @@ -133,7 +132,7 @@ class FutureTests: XCTestCase { func test_future_states_result_first_value_after() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let queue = DispatchQueue(label: "") let future = Future() let expectation = expectation(description: "") @@ -158,7 +157,7 @@ class FutureTests: XCTestCase { func test_future_states_value_first_result_after() throws { // Given - let anyValue = Int.random(in: Int.min...Int.max) + let anyValue = Int.random(in: Int.min ... Int.max) let future = Future() // When diff --git a/Tests/HarmonyTests/InMemoryDataSourceTests.swift b/Tests/HarmonyTests/InMemoryDataSourceTests.swift index 39e37944..b9ace276 100644 --- a/Tests/HarmonyTests/InMemoryDataSourceTests.swift +++ b/Tests/HarmonyTests/InMemoryDataSourceTests.swift @@ -15,12 +15,11 @@ // import Foundation +import Harmony import Nimble import XCTest -import Harmony class InMemoryDataSourceTests: XCTestCase { - private func provideEmptyDataSource() -> InMemoryDataSource { return InMemoryDataSource() } @@ -68,7 +67,6 @@ class InMemoryDataSourceTests: XCTestCase { try dataSource.get(query).result.get() } .to(throwError(errorType: CoreError.NotFound.self)) - } func test_get_value_not_found() throws { @@ -187,5 +185,4 @@ class InMemoryDataSourceTests: XCTestCase { // Then .to(throwError(errorType: CoreError.NotFound.self)) // The old value (list) is not there anymore } - } diff --git a/Tests/HarmonyTests/TimedCacheDataSourceTests.swift b/Tests/HarmonyTests/TimedCacheDataSourceTests.swift index 80d7c4e8..945265c7 100644 --- a/Tests/HarmonyTests/TimedCacheDataSourceTests.swift +++ b/Tests/HarmonyTests/TimedCacheDataSourceTests.swift @@ -6,13 +6,12 @@ // import Foundation +import Harmony import Nimble import XCTest -import Harmony // TODO: Improve TimedCacheDataSourceTests to take into account expiration date. Use a spy to check wether the value is obtained from cache or not. class TimedCacheDataSourceTests: XCTestCase { - private func provideEmptyDataSource() -> TimedCacheDataSource> { return TimedCacheDataSource(InMemoryDataSource()) } @@ -60,7 +59,6 @@ class TimedCacheDataSourceTests: XCTestCase { try dataSource.get(query).result.get() } .to(throwError(errorType: CoreError.NotFound.self)) - } func test_get_value_not_found() throws { @@ -179,5 +177,4 @@ class TimedCacheDataSourceTests: XCTestCase { // Then .to(throwError(errorType: CoreError.NotFound.self)) // The old value (list) is not there anymore } - }