From 5b89c93a973bdf7c67371573f780c3138dc589e8 Mon Sep 17 00:00:00 2001 From: StanislavDevIOS Date: Sun, 31 Jul 2022 11:59:47 +0300 Subject: [PATCH] Implement a linter --- .swiftlint.yml | 22 +++++++ Adamant.xcodeproj/project.pbxproj | 38 ++++++++---- Adamant/AppDelegate.swift | 6 +- .../BaseAccount+CoreDataProperties.swift | 1 - .../BaseTransaction+CoreDataProperties.swift | 1 - .../ChatTransaction+CoreDataProperties.swift | 1 - .../Chatroom+CoreDataProperties.swift | 1 - .../CoreDataAccount+CoreDataProperties.swift | 1 - .../DummyAccount+CoreDataProperties.swift | 2 - ...essageTransaction+CoreDataProperties.swift | 1 - ...essageTransaction+CoreDataProperties.swift | 1 - ...ansferTransaction+CoreDataProperties.swift | 1 - Adamant/Helpers/String+adamant.swift | 6 +- Adamant/Models/AdamantMessage.swift | 2 - Adamant/Models/BTCRawTransaction.swift | 7 +-- Adamant/Models/EthTransaction.swift | 4 -- Adamant/ServiceProtocols/AccountService.swift | 10 ---- .../ServiceProtocols/AddressBookService.swift | 2 - Adamant/ServiceProtocols/ApiService.swift | 6 -- Adamant/ServiceProtocols/CellFactory.swift | 1 - .../CurrencyInfoService.swift | 3 - .../DataProviders/AccountsProvider.swift | 5 +- .../DataProviders/ChatsProvider.swift | 11 +--- .../DataProviders/DataProvider.swift | 3 +- .../DataProviders/TransfersProvider.swift | 2 - Adamant/ServiceProtocols/DialogService.swift | 1 - .../NotificationsService.swift | 3 - .../RichMessageProvider.swift | 1 - Adamant/ServiceProtocols/Router.swift | 2 - Adamant/Services/AdamantAccountService.swift | 13 +--- .../Services/AdamantAddressBookService.swift | 7 --- .../Services/AdamantCurrencyInfoService.swift | 6 +- Adamant/Services/AdamantDialogService.swift | 8 +-- Adamant/Services/AdamantNodesSource.swift | 5 +- .../Services/AdamantNotificationService.swift | 6 +- Adamant/Services/AdamantReachability.swift | 4 +- .../ApiService/AdamantApi+Delegates.swift | 1 - .../ApiService/AdamantApi+Peers.swift | 1 - .../ApiService/AdamantApiService.swift | 1 - .../AdamantAccountsProvider.swift | 15 ++--- ...AdamantChatsProvider+backgroundFetch.swift | 2 +- .../AdamantChatsProvider+fakeMessages.swift | 7 +-- .../AdamantChatsProvider+search.swift | 9 +-- .../DataProviders/AdamantChatsProvider.swift | 45 ++++++-------- ...antTransfersProvider+backgroundFetch.swift | 2 +- .../AdamantTransfersProvider.swift | 29 ++++----- Adamant/Services/NativeCore+AdamantCore.swift | 1 - Adamant/Services/RepeaterService.swift | 2 +- .../SocketService/AdamantSocketService.swift | 2 +- Adamant/SharedViews/FullscreenAlertView.swift | 1 - .../TransferCollectionViewCell.swift | 2 +- .../AccountViewController+StayIn.swift | 5 -- .../Account/AccountViewController.swift | 35 ++++------- .../Chats/ChatListViewController.swift | 18 ++---- .../Chats/ChatViewController+MessageKit.swift | 16 ++--- .../Stories/Chats/ChatViewController.swift | 19 ++---- .../Chats/ComplexTransferViewController.swift | 2 - .../Stories/Chats/NewChatViewController.swift | 28 ++++----- .../Chats/SearchResultsViewController.swift | 2 +- .../Delegates/AdamantDelegateCell.swift | 2 - .../DelegateDetailsViewController.swift | 11 +--- .../DelegatesListViewController.swift | 15 +---- .../Login/LoginViewController+Pinpad.swift | 2 - .../Login/LoginViewController+QR.swift | 1 - .../Stories/Login/LoginViewController.swift | 33 ++++------- .../NodeEditorViewController.swift | 15 ++--- .../NodesEditor/NodesEditorRoutes.swift | 1 - .../NodesEditor/NodesListViewController.swift | 25 +++----- .../Stories/Onboard/EulaViewController.swift | 4 +- Adamant/Stories/Onboard/OnboardRoutes.swift | 4 +- .../Onboard/OnboardViewController.swift | 4 +- .../Settings/AboutViewController.swift | 18 ++---- .../NotificationsViewController.swift | 10 ++-- .../Settings/PKGeneratorViewController.swift | 16 ++--- .../Settings/QRGeneratorViewController.swift | 14 ++--- .../SecurityViewController+StayIn.swift | 5 -- .../Settings/SecurityViewController.swift | 23 +++----- .../Stories/Shared/ButtonsStripeView.swift | 13 ++-- .../Shared/ShareQrViewController.swift | 15 +++-- .../Stories/SwiftyOnboard/SwiftyOnboard.swift | 19 +++--- Adamant/SwinjectDependencies.swift | 11 ++-- .../Utilities/AdamantUtilities+extended.swift | 2 - Adamant/Utilities/ByteBackpacker.swift | 10 +--- Adamant/Utilities/KeyboardManager.swift | 6 +- .../AdmTransactionDetailsViewController.swift | 6 +- .../AdmTransactionsViewController.swift | 7 +-- .../Adamant/AdmTransferViewController.swift | 15 +++-- .../Adamant/AdmWalletService+Send.swift | 1 - .../Wallets/Adamant/AdmWalletService.swift | 7 +-- .../Adamant/AdmWalletViewController.swift | 6 +- .../Adamant/BuyAndSellViewController.swift | 2 +- Adamant/Wallets/BalanceTableViewCell.swift | 1 - ...DashTransactionDetailsViewController.swift | 2 +- .../Dash/DashTransactionsViewController.swift | 5 +- .../Dash/DashTransferViewController.swift | 7 +-- .../Wallets/Dash/DashWalletService+Send.swift | 1 - Adamant/Wallets/Dash/DashWalletService.swift | 6 +- ...DogeTransactionDetailsViewController.swift | 2 +- .../Doge/DogeTransactionsViewController.swift | 6 +- .../Doge/DogeTransferViewController.swift | 7 +-- .../Wallets/Doge/DogeWalletService+Send.swift | 1 - Adamant/Wallets/Doge/DogeWalletService.swift | 6 +- .../ERC20TransactionsViewController.swift | 2 - .../ERC20/ERC20TransferViewController.swift | 8 +-- .../ERC20/ERC20WalletService+Send.swift | 1 - .../Wallets/ERC20/ERC20WalletService.swift | 10 ++-- .../EthTransactionsViewController.swift | 2 - .../Ethereum/EthTransferViewController.swift | 9 +-- .../Ethereum/EthWalletService+Send.swift | 1 - .../Wallets/Ethereum/EthWalletService.swift | 19 ++---- .../LskTransactionDetailsViewController.swift | 2 +- .../Lisk/LskTransactionsViewController.swift | 1 - .../Lisk/LskTransferViewController.swift | 9 +-- .../Wallets/Lisk/LskWalletService+Send.swift | 1 - Adamant/Wallets/Lisk/LskWalletService.swift | 12 ++-- ...TransactionDetailsViewControllerBase.swift | 35 ++++++----- .../Wallets/TransactionTableViewCell.swift | 4 -- .../TransactionsListViewControllerBase.swift | 7 +-- .../TransferViewControllerBase+Alert.swift | 4 +- .../TransferViewControllerBase+QR.swift | 1 - .../Wallets/TransferViewControllerBase.swift | 59 +++++++------------ Adamant/Wallets/WalletService.swift | 9 +-- .../Wallets/WalletViewControllerBase.swift | 16 ++--- AdamantShared/AdamantResources.swift | 2 +- AdamantShared/Core/Crypto.swift | 12 ++-- AdamantShared/Core/NativeAdamantCore.swift | 1 - .../ExtensionsTools/ExtensionsApi.swift | 6 +- .../Helpers/AdamantBalanceFormat.swift | 2 - AdamantShared/Helpers/AdamantUtilities.swift | 1 - AdamantShared/Helpers/Date+adamant.swift | 4 -- AdamantShared/Helpers/UIColor+adamant.swift | 2 - .../Localization/AdamantLocalized.swift | 1 - AdamantShared/Models/RichMessage.swift | 1 - AdamantShared/Models/ServerResponse.swift | 5 +- AdamantShared/Models/Transaction.swift | 1 - .../TransferBaseProvider.swift | 2 - .../Services/AdamantAvatarService.swift | 12 ++-- AdamantShared/Services/KeychainStore.swift | 1 - AdamantShared/View/WarningView.swift | 2 +- AdamantTests/AdamantUriBuilding.swift | 1 - AdamantTests/Core/JSAdamantCore.swift | 19 ++---- AdamantTests/Core/JSAdamantCoreTests.swift | 2 - AdamantTests/Core/JSModels.swift | 4 -- .../BitcoinKit/Scripts/AddressConverter.swift | 1 - .../BitcoinKit.Private.swift | 5 +- LiskKit/Package.swift | 2 +- .../Responses/NodeConstantsResponse.swift | 1 - .../API/Transactions/LocalTransaction.swift | 7 +-- .../Models/TransactionModel.swift | 2 +- LiskKit/Sources/Core/APIClient.swift | 2 +- LiskKit/Sources/Crypto/BytePacker.swift | 2 +- LiskKit/Sources/Crypto/Crypto.swift | 5 +- LiskKit/Sources/Crypto/SHA256.swift | 2 +- .../TransactionsTransferTests.swift | 2 +- LiskKit/Tests/LiskTestCase.swift | 4 +- .../NotificationViewController.swift | 8 +-- .../NotificationService.swift | 4 +- .../NotificationViewController.swift | 2 +- 158 files changed, 401 insertions(+), 747 deletions(-) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 000000000..3436ff6b6 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,22 @@ +disabled_rules: + - colon + - comma + - control_statement + - identifier_name + - line_length + - force_try + - type_name + - cyclomatic_complexity + - force_cast + - type_body_length + - trailing_whitespace + - function_body_length + - comment_spacing + - file_length + - large_tuple + - function_parameter_count + - shorthand_operator + - operator_whitespace + - no_fallthrough_only + - computed_accessors_order + - xctfail_message \ No newline at end of file diff --git a/Adamant.xcodeproj/project.pbxproj b/Adamant.xcodeproj/project.pbxproj index f5633c1ba..62d029b2b 100644 --- a/Adamant.xcodeproj/project.pbxproj +++ b/Adamant.xcodeproj/project.pbxproj @@ -15,10 +15,10 @@ 3AE89DDB2837F5D30051D3A9 /* ChatRoomsChats.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AE89DDA2837F5D30051D3A9 /* ChatRoomsChats.swift */; }; 3C06931576393125C61FB8F6 /* Pods_Adamant.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 33975C0D891698AA7E74EBCC /* Pods_Adamant.framework */; }; 41935848287841E20083363B /* MacOSDeterminer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41935847287841E20083363B /* MacOSDeterminer.swift */; }; - 41E857A42847ADA200BC0783 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E857A32847ADA200BC0783 /* AdamantSecret.swift */; }; - 41E857A52847ADA200BC0783 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E857A32847ADA200BC0783 /* AdamantSecret.swift */; }; - 41E857A62847ADA200BC0783 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E857A32847ADA200BC0783 /* AdamantSecret.swift */; }; - 41E857A72847ADA200BC0783 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E857A32847ADA200BC0783 /* AdamantSecret.swift */; }; + 41E14154288545B2002142A6 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E14153288545B2002142A6 /* AdamantSecret.swift */; }; + 41E14155288545B2002142A6 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E14153288545B2002142A6 /* AdamantSecret.swift */; }; + 41E14156288545B2002142A6 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E14153288545B2002142A6 /* AdamantSecret.swift */; }; + 41E14157288545B2002142A6 /* AdamantSecret.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41E14153288545B2002142A6 /* AdamantSecret.swift */; }; 553B1284281C6EE100FFF24C /* GCDUtilites.swift in Sources */ = {isa = PBXBuildFile; fileRef = 553B1283281C6EE100FFF24C /* GCDUtilites.swift */; }; 6403F5DB2272389800D58779 /* (null) in Sources */ = {isa = PBXBuildFile; }; 6403F5DE22723C6800D58779 /* DashMainnet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6403F5DD22723C6800D58779 /* DashMainnet.swift */; }; @@ -619,7 +619,7 @@ 3AE89DD82837F5BF0051D3A9 /* ChatRooms.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatRooms.swift; sourceTree = ""; }; 3AE89DDA2837F5D30051D3A9 /* ChatRoomsChats.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatRoomsChats.swift; sourceTree = ""; }; 41935847287841E20083363B /* MacOSDeterminer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacOSDeterminer.swift; sourceTree = ""; }; - 41E857A32847ADA200BC0783 /* AdamantSecret.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AdamantSecret.swift; sourceTree = ""; }; + 41E14153288545B2002142A6 /* AdamantSecret.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AdamantSecret.swift; sourceTree = ""; }; 4A4D67BD3DC89C07D1351248 /* Pods-AdmCore.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AdmCore.release.xcconfig"; path = "Target Support Files/Pods-AdmCore/Pods-AdmCore.release.xcconfig"; sourceTree = ""; }; 553B1283281C6EE100FFF24C /* GCDUtilites.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GCDUtilites.swift; sourceTree = ""; }; 6403F5DD22723C6800D58779 /* DashMainnet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashMainnet.swift; sourceTree = ""; }; @@ -1725,7 +1725,7 @@ E9D664C222A0037600733F8A /* View */, E957E123229B0C330019732A /* AdamantNotificationKeys.swift */, E9771D802299602D0099AAC7 /* AdamantResources.swift */, - 41E857A32847ADA200BC0783 /* AdamantSecret.swift */, + 41E14153288545B2002142A6 /* AdamantSecret.swift */, E957E170229C56EE0019732A /* Shared.xcassets */, ); path = AdamantShared; @@ -1993,6 +1993,7 @@ 629616F00016639A2AFC5FC7 /* [CP] Embed Pods Frameworks */, E96D64E62295CD4700CA5587 /* Embed App Extensions */, A5AC8E01262E0B030053A7E2 /* Embed Frameworks */, + 41E1415828854739002142A6 /* ShellScript */, ); buildRules = ( ); @@ -2305,6 +2306,23 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 41E1415828854739002142A6 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"error: SwiftLint does not exist, download it from https://github.com/realm/SwiftLint\"\n exit 1\nfi\n"; + }; 47866E9AB7D201F2CED0064C /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -2371,7 +2389,7 @@ E9079A92229DF1B80022CA0D /* UIColor+hex.swift in Sources */, E9079A8D229DF19A0022CA0D /* KeychainStore.swift in Sources */, E9079AA4229DF6850022CA0D /* AdamantUtilities.swift in Sources */, - 41E857A72847ADA200BC0783 /* AdamantSecret.swift in Sources */, + 41E14157288545B2002142A6 /* AdamantSecret.swift in Sources */, E951466C22A691EF007564D7 /* String+utilites.swift in Sources */, E9079A8F229DF1A40022CA0D /* Crypto.swift in Sources */, E9079A90229DF1A40022CA0D /* Mnemonic.swift in Sources */, @@ -2411,7 +2429,7 @@ E9256F5F2034C21100DE86E9 /* String+localized.swift in Sources */, 6414C18E217DF43100373FA6 /* String+adamant.swift in Sources */, E908472A2196FEA80095825D /* RichMessageTransaction+CoreDataClass.swift in Sources */, - 41E857A42847ADA200BC0783 /* AdamantSecret.swift in Sources */, + 41E14154288545B2002142A6 /* AdamantSecret.swift in Sources */, 64A223D620F760BB005157CB /* Localization.swift in Sources */, 64E1C82F222E95F6006C4DA7 /* DogeWallet.swift in Sources */, E9484B7D2285BAD9008E10F0 /* PrivateKeyGenerator.swift in Sources */, @@ -2754,7 +2772,7 @@ 64AE84622300012400F38FBD /* DashProvider.swift in Sources */, E957E16C229C53980019732A /* LskProvider.swift in Sources */, E9D664D022A009AB00733F8A /* AdamantLocalized.swift in Sources */, - 41E857A62847ADA200BC0783 /* AdamantSecret.swift in Sources */, + 41E14156288545B2002142A6 /* AdamantSecret.swift in Sources */, E957E14D229C3E530019732A /* Node.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2797,7 +2815,7 @@ E957E0ED229982FF0019732A /* Keypair.swift in Sources */, 6423038324B26CAF004CF3FE /* ERC20Token.swift in Sources */, E957E0FB229AB9310019732A /* AdamantProvider.swift in Sources */, - 41E857A52847ADA200BC0783 /* AdamantSecret.swift in Sources */, + 41E14155288545B2002142A6 /* AdamantSecret.swift in Sources */, E957E157229C3F840019732A /* ExtensionsApi.swift in Sources */, E957E0F722999BD50019732A /* TransferBaseProvider.swift in Sources */, E9771D9622996FEB0099AAC7 /* StateType.swift in Sources */, diff --git a/Adamant/AppDelegate.swift b/Adamant/AppDelegate.swift index f22f809e2..5900096cd 100644 --- a/Adamant/AppDelegate.swift +++ b/Adamant/AppDelegate.swift @@ -35,7 +35,6 @@ extension StoreKey { } } - // MARK: - Application @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -217,7 +216,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { dialogService.showError(withMessage: "Failed to register CurrencyInfoService autoupdate. Please, report a bug", error: nil) } - // MARK: 6. Logout reset NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedOut, object: nil, queue: OperationQueue.main) { [weak self] _ in // On logout, pop all navigators to root. @@ -343,7 +341,7 @@ extension AppDelegate: UNUserNotificationCenterDelegate { } } - //MARK: Open Chat From Notification + // MARK: Open Chat From Notification func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let transactionID = userInfo[AdamantNotificationUserInfoKeys.transactionId] as? String, let transactionRaw = userInfo[AdamantNotificationUserInfoKeys.transaction] as? String, @@ -410,7 +408,6 @@ extension AppDelegate: UNUserNotificationCenterDelegate { } } - // MARK: - Background Fetch extension AppDelegate { func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { @@ -470,7 +467,6 @@ extension AppDelegate { } } - // MARK: - Welcome messages extension AppDelegate { private func handleWelcomeMessages(notification: Notification) { diff --git a/Adamant/CoreData/BaseAccount+CoreDataProperties.swift b/Adamant/CoreData/BaseAccount+CoreDataProperties.swift index 5657d0d9f..17445fc33 100644 --- a/Adamant/CoreData/BaseAccount+CoreDataProperties.swift +++ b/Adamant/CoreData/BaseAccount+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension BaseAccount { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/BaseTransaction+CoreDataProperties.swift b/Adamant/CoreData/BaseTransaction+CoreDataProperties.swift index ac26de1d3..8ffb2211b 100644 --- a/Adamant/CoreData/BaseTransaction+CoreDataProperties.swift +++ b/Adamant/CoreData/BaseTransaction+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension BaseTransaction { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/ChatTransaction+CoreDataProperties.swift b/Adamant/CoreData/ChatTransaction+CoreDataProperties.swift index 0ed0cc2c0..d5da8484a 100644 --- a/Adamant/CoreData/ChatTransaction+CoreDataProperties.swift +++ b/Adamant/CoreData/ChatTransaction+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension ChatTransaction { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/Chatroom+CoreDataProperties.swift b/Adamant/CoreData/Chatroom+CoreDataProperties.swift index 49ab630b4..c44cb7f5c 100644 --- a/Adamant/CoreData/Chatroom+CoreDataProperties.swift +++ b/Adamant/CoreData/Chatroom+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension Chatroom { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/CoreDataAccount+CoreDataProperties.swift b/Adamant/CoreData/CoreDataAccount+CoreDataProperties.swift index e6c848674..4a60b59cd 100644 --- a/Adamant/CoreData/CoreDataAccount+CoreDataProperties.swift +++ b/Adamant/CoreData/CoreDataAccount+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension CoreDataAccount { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/DummyAccount+CoreDataProperties.swift b/Adamant/CoreData/DummyAccount+CoreDataProperties.swift index 00fdff1f8..05887eb88 100644 --- a/Adamant/CoreData/DummyAccount+CoreDataProperties.swift +++ b/Adamant/CoreData/DummyAccount+CoreDataProperties.swift @@ -10,12 +10,10 @@ import Foundation import CoreData - extension DummyAccount { @nonobjc public class func fetchRequest() -> NSFetchRequest { return NSFetchRequest(entityName: "DummyAccount") } - } diff --git a/Adamant/CoreData/MessageTransaction+CoreDataProperties.swift b/Adamant/CoreData/MessageTransaction+CoreDataProperties.swift index 0db63c902..babbf6cd6 100644 --- a/Adamant/CoreData/MessageTransaction+CoreDataProperties.swift +++ b/Adamant/CoreData/MessageTransaction+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension MessageTransaction { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/RichMessageTransaction+CoreDataProperties.swift b/Adamant/CoreData/RichMessageTransaction+CoreDataProperties.swift index 1ac9073d2..e25b775f2 100644 --- a/Adamant/CoreData/RichMessageTransaction+CoreDataProperties.swift +++ b/Adamant/CoreData/RichMessageTransaction+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension RichMessageTransaction { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/CoreData/TransferTransaction+CoreDataProperties.swift b/Adamant/CoreData/TransferTransaction+CoreDataProperties.swift index c87032ccc..f130c41cf 100644 --- a/Adamant/CoreData/TransferTransaction+CoreDataProperties.swift +++ b/Adamant/CoreData/TransferTransaction+CoreDataProperties.swift @@ -10,7 +10,6 @@ import Foundation import CoreData - extension TransferTransaction { @nonobjc public class func fetchRequest() -> NSFetchRequest { diff --git a/Adamant/Helpers/String+adamant.swift b/Adamant/Helpers/String+adamant.swift index f47a55ecb..ecc5b180c 100644 --- a/Adamant/Helpers/String+adamant.swift +++ b/Adamant/Helpers/String+adamant.swift @@ -34,8 +34,8 @@ extension String { func getLegacyAdamantAddress() -> AdamantAddress? { let address: String? - var name: String? = nil - var message: String? = nil + var name: String? + var message: String? if let uri = AdamantUriTools.decode(uri: self) { switch uri { @@ -54,7 +54,7 @@ extension String { } } - case .passphrase(_): + case .passphrase: address = nil } } else { diff --git a/Adamant/Models/AdamantMessage.swift b/Adamant/Models/AdamantMessage.swift index 0a3264236..0bd9ef4b3 100644 --- a/Adamant/Models/AdamantMessage.swift +++ b/Adamant/Models/AdamantMessage.swift @@ -18,7 +18,6 @@ enum AdamantMessage { case richMessage(payload: RichMessage) } - // MARK: - Fee extension AdamantMessage { static private let textFee = Decimal(sign: .plus, exponent: -3, significand: 1) @@ -38,7 +37,6 @@ extension AdamantMessage { } } - // MARK: - ChatType extension AdamantMessage { var chatType: ChatType { diff --git a/Adamant/Models/BTCRawTransaction.swift b/Adamant/Models/BTCRawTransaction.swift index 59c7564e3..7743c45d5 100644 --- a/Adamant/Models/BTCRawTransaction.swift +++ b/Adamant/Models/BTCRawTransaction.swift @@ -68,8 +68,8 @@ struct BTCRawTransaction { } } - let senders = Set(inputs.map { $0.sender } ) - let recipients = Set(outputs.compactMap { $0.addresses.first } ) + let senders = Set(inputs.map { $0.sender }) + let recipients = Set(outputs.compactMap { $0.addresses.first }) let sender: String let recipient: String @@ -98,7 +98,6 @@ struct BTCRawTransaction { } } - // MARK: Inputs if myInputs.count > 0 { let inputTransaction = T(txId: txId, @@ -277,7 +276,7 @@ struct BTCOutput: Decodable { self.value = value } else if let raw = try? container.decode(Decimal.self, forKey: .value) { self.value = raw - } else { + } else { self.value = 0 } diff --git a/Adamant/Models/EthTransaction.swift b/Adamant/Models/EthTransaction.swift index d5faaa9f1..00c346cda 100644 --- a/Adamant/Models/EthTransaction.swift +++ b/Adamant/Models/EthTransaction.swift @@ -38,7 +38,6 @@ extension EthResponse: Decodable { } } - // MARK: - Eth Transaction struct EthTransaction { @@ -57,7 +56,6 @@ struct EthTransaction { var isOutgoing: Bool = false } - // MARK: Decodable extension EthTransaction: Decodable { enum CodingKeys: String, CodingKey { @@ -131,7 +129,6 @@ extension EthTransaction: Decodable { } } - // MARK: - TransactionDetails extension EthTransaction: TransactionDetails { static var defaultCurrencySymbol: String? { return EthWalletService.currencySymbol } @@ -202,7 +199,6 @@ extension EthereumTransaction { } } - // MARK: Sample JSON /* { diff --git a/Adamant/ServiceProtocols/AccountService.swift b/Adamant/ServiceProtocols/AccountService.swift index 352ee7d7a..f78230549 100644 --- a/Adamant/ServiceProtocols/AccountService.swift +++ b/Adamant/ServiceProtocols/AccountService.swift @@ -29,7 +29,6 @@ extension Notification.Name { /// - Adamant.AccountService.newStayInState with new state static let stayInChanged = Notification.Name("adamant.accountService.stayInChanged") - /// Raised when wallets collection updated /// /// UserInfo: @@ -41,7 +40,6 @@ extension Notification.Name { } } - // MARK: - Localization extension String.adamantLocalized { struct accountService { @@ -51,7 +49,6 @@ extension String.adamantLocalized { } } - /// - loggedAccountAddress: Newly logged account's address extension AdamantUserInfoKey { struct AccountService { @@ -141,7 +138,6 @@ extension AccountServiceError: RichError { } } - // MARK: - Protocol protocol AccountService: AnyObject { // MARK: State @@ -150,11 +146,9 @@ protocol AccountService: AnyObject { var account: AdamantAccount? { get } var keypair: Keypair? { get } - // MARK: Wallets var wallets: [WalletService] { get } - // MARK: Account functions /// Update logged account info @@ -167,7 +161,6 @@ protocol AccountService: AnyObject { /// Login into Adamant using passphrase. func loginWith(passphrase: String, completion: @escaping (AccountServiceResult) -> Void) - /// Login into Adamant using previously logged account func loginWithStoredAccount(completion: @escaping (AccountServiceResult) -> Void) @@ -177,7 +170,6 @@ protocol AccountService: AnyObject { /// Reload current wallets state func reloadWallets() - // MARK: Stay in functions /// There is a stored account information in secured store @@ -186,7 +178,6 @@ protocol AccountService: AnyObject { /// Use TouchID or FaceID to log in var useBiometry: Bool { get set } - /// Save account data and use pincode to login /// /// - Parameters: @@ -194,7 +185,6 @@ protocol AccountService: AnyObject { /// - completion: completion handler func setStayLoggedIn(pin: String, completion: @escaping (AccountServiceResult) -> Void) - /// Remove stored data func dropSavedAccount() diff --git a/Adamant/ServiceProtocols/AddressBookService.swift b/Adamant/ServiceProtocols/AddressBookService.swift index b4c1a6351..d58dcee1b 100644 --- a/Adamant/ServiceProtocols/AddressBookService.swift +++ b/Adamant/ServiceProtocols/AddressBookService.swift @@ -35,7 +35,6 @@ extension AdamantUserInfoKey { } } - // MARK: - Result and Errors enum AddressBookServiceResult { @@ -81,7 +80,6 @@ extension AddressBookServiceError: RichError { } } - // MARK: - protocol AddressBookService: AnyObject { // MARK: Work with Address book diff --git a/Adamant/ServiceProtocols/ApiService.swift b/Adamant/ServiceProtocols/ApiService.swift index 222887ec2..a3ad743ef 100644 --- a/Adamant/ServiceProtocols/ApiService.swift +++ b/Adamant/ServiceProtocols/ApiService.swift @@ -104,7 +104,6 @@ extension ApiServiceError: Equatable { } } - // - MARK: ApiService protocol ApiService: AnyObject { @@ -127,7 +126,6 @@ protocol ApiService: AnyObject { func getNodeVersion(url: URL, completion: @escaping (ApiServiceResult) -> Void) - // MARK: - Accounts func newAccount(byPublicKey publicKey: String, completion: @escaping (ApiServiceResult) -> Void) @@ -135,18 +133,15 @@ protocol ApiService: AnyObject { func getAccount(byPublicKey publicKey: String, completion: @escaping (ApiServiceResult) -> Void) func getAccount(byAddress address: String, completion: @escaping (ApiServiceResult) -> Void) - // MARK: - Keys func getPublicKey(byAddress address: String, completion: @escaping (ApiServiceResult) -> Void) - // MARK: - Transactions func getTransaction(id: UInt64, completion: @escaping (ApiServiceResult) -> Void) func getTransactions(forAccount: String, type: TransactionType, fromHeight: Int64?, offset: Int?, limit: Int?, completion: @escaping (ApiServiceResult<[Transaction]>) -> Void) - // MARK: - Chats Rooms func getChatRooms(address: String, offset: Int?, completion: @escaping (ApiServiceResult) -> Void) @@ -156,7 +151,6 @@ protocol ApiService: AnyObject { func transferFunds(sender: String, recipient: String, amount: Decimal, keypair: Keypair, completion: @escaping (ApiServiceResult) -> Void) - // MARK: - States /// - Returns: Transaction ID diff --git a/Adamant/ServiceProtocols/CellFactory.swift b/Adamant/ServiceProtocols/CellFactory.swift index d3e3f6643..662799f1f 100644 --- a/Adamant/ServiceProtocols/CellFactory.swift +++ b/Adamant/ServiceProtocols/CellFactory.swift @@ -20,7 +20,6 @@ struct SharedCell: Equatable, Hashable { } } - protocol CellFactory: AnyObject { func nib(for sharedCell: SharedCell) -> UINib? func cellInstance(for sharedCell: SharedCell) -> UITableViewCell? diff --git a/Adamant/ServiceProtocols/CurrencyInfoService.swift b/Adamant/ServiceProtocols/CurrencyInfoService.swift index 86c00d178..8eecaccf2 100644 --- a/Adamant/ServiceProtocols/CurrencyInfoService.swift +++ b/Adamant/ServiceProtocols/CurrencyInfoService.swift @@ -14,7 +14,6 @@ extension Notification.Name { } } - // MARK: - Currencies enum Currency: String { case RUB = "RUB" @@ -36,7 +35,6 @@ enum Currency: String { static var `default` = Currency.USD } - // MARK: - protocol protocol CurrencyInfoService: AnyObject { var currentCurrency: Currency { get set } @@ -50,7 +48,6 @@ protocol CurrencyInfoService: AnyObject { func getHistory(for coin: String, timestamp: Date, completion: @escaping (ApiServiceResult<[String:Decimal]?>) -> Void) } - // MARK: - AdamantBalanceFormat fiat formatter extension AdamantBalanceFormat { /// General fiat currency formatter, without currency specified diff --git a/Adamant/ServiceProtocols/DataProviders/AccountsProvider.swift b/Adamant/ServiceProtocols/DataProviders/AccountsProvider.swift index 12aa9a883..9e9ae6b94 100644 --- a/Adamant/ServiceProtocols/DataProviders/AccountsProvider.swift +++ b/Adamant/ServiceProtocols/DataProviders/AccountsProvider.swift @@ -20,7 +20,7 @@ enum AccountsProviderResult { var localized: String { switch self { - case .success(_), .dummy(_): + case .success, .dummy: return "" case .notFound(let address): @@ -29,7 +29,7 @@ enum AccountsProviderResult { case .invalidAddress(let address): return String.localizedStringWithFormat(NSLocalizedString("AccountsProvider.Error.AddressNotValidFormat", comment: "AccountsProvider: Address not valid error, %@ for address"), address) - case .notInitiated(_): + case .notInitiated: return String.adamantLocalized.sharedErrors.accountNotInitiated case .serverError(let error): @@ -69,7 +69,6 @@ protocol AccountsProvider { /// Check locally if has account with specified address func hasAccount(address: String, completion: @escaping (Bool) -> Void) - /// Request Dummy account, if account wasn't found or initiated func getDummyAccount(for address: String, completion: @escaping (AccountsProviderDummyAccountResult) -> Void) } diff --git a/Adamant/ServiceProtocols/DataProviders/ChatsProvider.swift b/Adamant/ServiceProtocols/DataProviders/ChatsProvider.swift index f6d1b57d6..dfb22ca33 100644 --- a/Adamant/ServiceProtocols/DataProviders/ChatsProvider.swift +++ b/Adamant/ServiceProtocols/DataProviders/ChatsProvider.swift @@ -9,7 +9,6 @@ import Foundation import CoreData - // MARK: - Callbacks enum ChatsProviderResult { @@ -71,7 +70,7 @@ extension ChatsProviderError: RichError { case .internalError(let error): return String.adamantLocalized.sharedErrors.internalError(message: error.localizedDescription) - case .accountNotInitiated(_): + case .accountNotInitiated: return String.adamantLocalized.sharedErrors.accountNotInitiated } } @@ -123,7 +122,6 @@ enum ValidateMessageResult { } } - // MARK: - Notifications extension Notification.Name { struct AdamantChatsProvider { @@ -136,7 +134,6 @@ extension Notification.Name { } } - // MARK: - Notification UserInfo keys extension AdamantUserInfoKey { struct ChatProvider { @@ -151,7 +148,6 @@ extension AdamantUserInfoKey { } } - // MARK: - SecuredStore keys extension StoreKey { struct chatProvider { @@ -163,7 +159,6 @@ extension StoreKey { } } - // MARK: - Protocol protocol ChatsProvider: DataProvider { // MARK: - Properties @@ -184,8 +179,8 @@ protocol ChatsProvider: DataProvider { // MARK: - Getting chats and messages func getChatroomsController() -> NSFetchedResultsController func getChatController(for chatroom: Chatroom) -> NSFetchedResultsController - func getChatRooms(offset: Int?, completion: (() ->())?) - func getChatMessages(with addressRecipient: String, offset: Int?, completion: ((Int) ->())?) + func getChatRooms(offset: Int?, completion: (() ->Void)?) + func getChatMessages(with addressRecipient: String, offset: Int?, completion: ((Int) ->Void)?) /// Unread messages controller. Sections by chatroom. func getUnreadMessagesController() -> NSFetchedResultsController diff --git a/Adamant/ServiceProtocols/DataProviders/DataProvider.swift b/Adamant/ServiceProtocols/DataProviders/DataProvider.swift index a3628358c..703ff7de1 100644 --- a/Adamant/ServiceProtocols/DataProviders/DataProvider.swift +++ b/Adamant/ServiceProtocols/DataProviders/DataProvider.swift @@ -24,7 +24,6 @@ protocol DataProvider: AnyObject { func reset() } - // MARK: - Status Equatable extension State: Equatable { @@ -35,7 +34,7 @@ extension State: Equatable { case (.updating, .updating): return true case (.upToDate, .upToDate): return true - case (.failedToUpdate(_), .failedToUpdate(_)): return true + case (.failedToUpdate, .failedToUpdate): return true default: return false } diff --git a/Adamant/ServiceProtocols/DataProviders/TransfersProvider.swift b/Adamant/ServiceProtocols/DataProviders/TransfersProvider.swift index bfbd190b0..5781eb715 100644 --- a/Adamant/ServiceProtocols/DataProviders/TransfersProvider.swift +++ b/Adamant/ServiceProtocols/DataProviders/TransfersProvider.swift @@ -79,7 +79,6 @@ extension TransfersProviderError: RichError { } } - } extension Notification.Name { @@ -92,7 +91,6 @@ extension Notification.Name { static let initialSyncFinished = Notification.Name("adamant.transfersProvider.initialSyncFinished") - private init() {} } } diff --git a/Adamant/ServiceProtocols/DialogService.swift b/Adamant/ServiceProtocols/DialogService.swift index 7f286e927..5c8f54fa4 100644 --- a/Adamant/ServiceProtocols/DialogService.swift +++ b/Adamant/ServiceProtocols/DialogService.swift @@ -99,7 +99,6 @@ protocol DialogService: AnyObject { /// Present view controller modally func present(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) - // MARK: - Toast messages /// Show pop-up message func showToastMessage(_ message: String) diff --git a/Adamant/ServiceProtocols/NotificationsService.swift b/Adamant/ServiceProtocols/NotificationsService.swift index 86f756398..6962cac75 100644 --- a/Adamant/ServiceProtocols/NotificationsService.swift +++ b/Adamant/ServiceProtocols/NotificationsService.swift @@ -50,7 +50,6 @@ enum NotificationsMode: Int { } } - /// Supported notification types /// /// - message: text message @@ -98,7 +97,6 @@ extension Notification.Name { } } - extension AdamantUserInfoKey { struct NotificationsService { static let newNotificationsMode = "adamant.notificationsService.notificationsMode" @@ -107,7 +105,6 @@ extension AdamantUserInfoKey { } } - // MARK: - Protocol enum NotificationsServiceResult { case success diff --git a/Adamant/ServiceProtocols/RichMessageProvider.swift b/Adamant/ServiceProtocols/RichMessageProvider.swift index 000969d5d..d0579e232 100644 --- a/Adamant/ServiceProtocols/RichMessageProvider.swift +++ b/Adamant/ServiceProtocols/RichMessageProvider.swift @@ -35,7 +35,6 @@ protocol RichMessageProvider: AnyObject { func cell(for message: MessageType, isFromCurrentSender: Bool, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UICollectionViewCell } - protocol RichMessageProviderWithStatusCheck: RichMessageProvider { func statusFor(transaction: RichMessageTransaction, completion: @escaping (WalletServiceResult) -> Void) diff --git a/Adamant/ServiceProtocols/Router.swift b/Adamant/ServiceProtocols/Router.swift index 897b2122c..86d06290a 100644 --- a/Adamant/ServiceProtocols/Router.swift +++ b/Adamant/ServiceProtocols/Router.swift @@ -9,7 +9,6 @@ import UIKit import Swinject - // MARK: - Adamant Scene struct AdamantScene { let identifier: String @@ -21,7 +20,6 @@ struct AdamantScene { } } - // MARK: - Adamant Router protocol Router: AnyObject { func get(scene: AdamantScene) -> UIViewController diff --git a/Adamant/Services/AdamantAccountService.swift b/Adamant/Services/AdamantAccountService.swift index ad1c40d8f..f415f75b5 100644 --- a/Adamant/Services/AdamantAccountService.swift +++ b/Adamant/Services/AdamantAccountService.swift @@ -58,7 +58,6 @@ class AdamantAccountService: AccountService { } } - // MARK: Properties private(set) var state: AccountServiceState = .notLogged @@ -115,7 +114,6 @@ class AdamantAccountService: AccountService { let erc20WalletServices = ERC20Token.supportedTokens.map { ERC20WalletService(token: $0) } wallets.append(contentsOf: erc20WalletServices) - //LskWalletService(mainnet: false) // Testnet // wallets.append(contentsOf: LskWalletService(mainnet: false)) @@ -248,7 +246,6 @@ extension AdamantAccountService { } } - // MARK: - AccountService extension AdamantAccountService { // MARK: Update logged account info @@ -309,7 +306,6 @@ extension AdamantAccountService { } } - // MARK: - Creating account extension AdamantAccountService { // MARK: passphrase @@ -326,10 +322,10 @@ extension AdamantAccountService { self.apiService.getAccount(byPublicKey: publicKey) { [weak self] result in switch result { - case .success(_): + case .success: completion(.failure(.wrongPassphrase)) - case .failure(_): + case .failure: if let apiService = self?.apiService { apiService.newAccount(byPublicKey: publicKey) { result in switch result { @@ -444,7 +440,6 @@ extension AdamantAccountService { completion(.failure(.invalidPassphrase)) } - // MARK: Keypair private func loginWith(keypair: Keypair, completion: @escaping (AccountServiceResult) -> Void) { stateSemaphore.wait() @@ -505,7 +500,6 @@ extension AdamantAccountService { } } - // MARK: - Log Out extension AdamantAccountService { func logout() { @@ -536,7 +530,6 @@ extension AdamantAccountService { } } - // MARK: - Secured Store extension StoreKey { fileprivate struct accountService { @@ -551,7 +544,7 @@ extension StoreKey { } } -fileprivate enum Key { +private enum Key { case publicKey case privateKey case pin diff --git a/Adamant/Services/AdamantAddressBookService.swift b/Adamant/Services/AdamantAddressBookService.swift index 058b4a930..d010f3575 100644 --- a/Adamant/Services/AdamantAddressBookService.swift +++ b/Adamant/Services/AdamantAddressBookService.swift @@ -13,7 +13,6 @@ class AdamantAddressBookService: AddressBookService { let addressBookKey = "contact_list" let waitTime: TimeInterval = 20.0 // in sec - // MARK: - Dependencies var apiService: ApiService! @@ -21,7 +20,6 @@ class AdamantAddressBookService: AddressBookService { var accountService: AccountService! var dialogService: DialogService! - // MARK: - Properties var addressBook: [String:String] = [String:String]() @@ -140,7 +138,6 @@ class AdamantAddressBookService: AddressBookService { userInfo: [AdamantUserInfoKey.AddressBook.changes: changes]) } - // MARK: - Updating func update() { @@ -204,7 +201,6 @@ class AdamantAddressBookService: AddressBookService { } } - // MARK: - Saving func saveIfNeeded() { @@ -228,7 +224,6 @@ class AdamantAddressBookService: AddressBookService { } isChangingSemaphore.signal() - // Background task savingBookTaskId = UIApplication.shared.beginBackgroundTask { UIApplication.shared.endBackgroundTask(self.savingBookTaskId) @@ -312,7 +307,6 @@ class AdamantAddressBookService: AddressBookService { } } - // MARK: - Getting address book private enum GetAddressBookResult { case success([String:String]) @@ -359,7 +353,6 @@ class AdamantAddressBookService: AddressBookService { } } - // MARK: - Tools extension AdamantAddressBookService { private static func processAddressBook(rawBook: [String:Any]) -> [String:String] { diff --git a/Adamant/Services/AdamantCurrencyInfoService.swift b/Adamant/Services/AdamantCurrencyInfoService.swift index b6e2972a6..43c649a0e 100644 --- a/Adamant/Services/AdamantCurrencyInfoService.swift +++ b/Adamant/Services/AdamantCurrencyInfoService.swift @@ -16,7 +16,6 @@ extension StoreKey { } } - // MARK: - Service class AdamantCurrencyInfoService: CurrencyInfoService { // MARK: - API @@ -43,7 +42,7 @@ class AdamantCurrencyInfoService: CurrencyInfoService { // MARK: - Properties private static let historyThreshold = Double(exactly: 60*60*24)! - private var rateCoins: [String]? = nil + private var rateCoins: [String]? private var rates = [String: Decimal]() private let defaultResponseDispatchQueue = DispatchQueue(label: "com.adamant.info-coins-response-queue", qos: .utility, attributes: [.concurrent]) @@ -89,7 +88,7 @@ class AdamantCurrencyInfoService: CurrencyInfoService { // MARK: - Observers func addObservers() { - observerActive = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] notification in + observerActive = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.update() } } @@ -187,7 +186,6 @@ class AdamantCurrencyInfoService: CurrencyInfoService { } } - // MARK: - Server responses struct CoinInfoServiceResponseGet: Decodable { enum CodingKeys: String, CodingKey { diff --git a/Adamant/Services/AdamantDialogService.swift b/Adamant/Services/AdamantDialogService.swift index 996622c86..4da1f21de 100644 --- a/Adamant/Services/AdamantDialogService.swift +++ b/Adamant/Services/AdamantDialogService.swift @@ -27,7 +27,6 @@ class AdamantDialogService: DialogService { } } - // MARK: - Modal dialogs extension AdamantDialogService { func present(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { @@ -63,7 +62,6 @@ extension AdamantDialogService { } } - // MARK: - Toast extension AdamantDialogService { func showToastMessage(_ message: String) { @@ -75,7 +73,6 @@ extension AdamantDialogService { } } - // MARK: - Indicators extension AdamantDialogService { func showProgress(withMessage message: String?, userInteractionEnable enabled: Bool) { @@ -195,7 +192,6 @@ extension AdamantDialogService { } } - // MARK: - Notifications extension AdamantDialogService { func showNotification(title: String?, message: String?, image: UIImage?, tapHandler: (() -> Void)?) { @@ -211,7 +207,6 @@ extension AdamantDialogService { } } - // MAKR: - Activity controllers extension AdamantDialogService { func presentShareAlertFor(string: String, types: [ShareType], excludedActivityTypes: [UIActivity.ActivityType]?, animated: Bool, from: UIView?, completion: (() -> Void)?) { @@ -368,7 +363,6 @@ extension AdamantDialogService { } } - // MARK: - Alerts fileprivate extension UIAlertAction.Style { func asPMAlertAction() -> PMAlertActionStyle { @@ -497,7 +491,7 @@ extension AdamantDialogService { } } -fileprivate class MailDelegate: NSObject, MFMailComposeViewControllerDelegate { +private class MailDelegate: NSObject, MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } diff --git a/Adamant/Services/AdamantNodesSource.swift b/Adamant/Services/AdamantNodesSource.swift index f9a85a1a0..24248a196 100644 --- a/Adamant/Services/AdamantNodesSource.swift +++ b/Adamant/Services/AdamantNodesSource.swift @@ -17,7 +17,6 @@ class AdamantNodesSource: NodesSource { } } - // MARK: - Properties var nodes: [Node] { didSet { @@ -34,7 +33,6 @@ class AdamantNodesSource: NodesSource { private var currentNodes: [Node] = [Node]() - // MARK: - Ctor init(defaultNodes: [Node]) { @@ -43,7 +41,6 @@ class AdamantNodesSource: NodesSource { self.currentNodes = defaultNodes } - // MARK: - Functions func getNewNode() -> Node { @@ -138,7 +135,7 @@ class AdamantNodesSource: NodesSource { self.apiService.getNodeVersion(url: url) { result in switch result { - case .success(_): + case .success: testState = .passed case .failure(let error): diff --git a/Adamant/Services/AdamantNotificationService.swift b/Adamant/Services/AdamantNotificationService.swift index 6779d99df..5e4898121 100644 --- a/Adamant/Services/AdamantNotificationService.swift +++ b/Adamant/Services/AdamantNotificationService.swift @@ -29,7 +29,6 @@ class AdamantNotificationsService: NotificationsService { var securedStore: SecuredStore! weak var accountService: AccountService? - // MARK: Properties private(set) var notificationsMode: NotificationsMode = .disabled private(set) var customBadgeNumber = 0 @@ -37,7 +36,7 @@ class AdamantNotificationsService: NotificationsService { private var isBackgroundSession = false private var backgroundNotifications = 0 - private var preservedBadgeNumber: Int? = nil + private var preservedBadgeNumber: Int? // MARK: Lifecycle init() { @@ -76,7 +75,6 @@ class AdamantNotificationsService: NotificationsService { } } - // MARK: - Notifications mode { extension AdamantNotificationsService { func setNotificationsMode(_ mode: NotificationsMode, completion: ((NotificationsServiceResult) -> Void)?) { @@ -159,7 +157,6 @@ extension AdamantNotificationsService { } } - // MARK: - Posting & removing Notifications extension AdamantNotificationsService { func showNotification(title: String, body: String, type: AdamantNotificationType) { @@ -228,7 +225,6 @@ extension AdamantNotificationsService { } } - // MARK: - Background batch notifications extension AdamantNotificationsService { func startBackgroundBatchNotifications() { diff --git a/Adamant/Services/AdamantReachability.swift b/Adamant/Services/AdamantReachability.swift index 92ddfe1b4..a876819b4 100644 --- a/Adamant/Services/AdamantReachability.swift +++ b/Adamant/Services/AdamantReachability.swift @@ -34,8 +34,8 @@ class AdamantReachability: ReachabilityMonitor { private var cellularStatus: NWPath.Status = .satisfied var connection: AdamantConnection { - if wifiStatus == .satisfied { return AdamantConnection.wifi } - if cellularStatus == .satisfied { return AdamantConnection.cellular } + if wifiStatus == .satisfied { return AdamantConnection.wifi } + if cellularStatus == .satisfied { return AdamantConnection.cellular } return AdamantConnection.none } diff --git a/Adamant/Services/ApiService/AdamantApi+Delegates.swift b/Adamant/Services/ApiService/AdamantApi+Delegates.swift index 2ad22432b..e484b4170 100644 --- a/Adamant/Services/ApiService/AdamantApi+Delegates.swift +++ b/Adamant/Services/ApiService/AdamantApi+Delegates.swift @@ -131,7 +131,6 @@ extension AdamantApiService { } completion(.success(forgingTime)) - break case .failure(let error): diff --git a/Adamant/Services/ApiService/AdamantApi+Peers.swift b/Adamant/Services/ApiService/AdamantApi+Peers.swift index 5518d904e..9d95707de 100644 --- a/Adamant/Services/ApiService/AdamantApi+Peers.swift +++ b/Adamant/Services/ApiService/AdamantApi+Peers.swift @@ -15,7 +15,6 @@ extension AdamantApiService.ApiCommands { ) } - // MARK: - Peers extension AdamantApiService { func getNodeVersion(url: URL, completion: @escaping (ApiServiceResult) -> Void) { diff --git a/Adamant/Services/ApiService/AdamantApiService.swift b/Adamant/Services/ApiService/AdamantApiService.swift index 802d4c4a0..33d868d92 100644 --- a/Adamant/Services/ApiService/AdamantApiService.swift +++ b/Adamant/Services/ApiService/AdamantApiService.swift @@ -88,7 +88,6 @@ class AdamantApiService: ApiService { let defaultResponseDispatchQueue = DispatchQueue(label: "com.adamant.response-queue", qos: .utility, attributes: [.concurrent]) - // MARK: - Init init() { NotificationCenter.default.addObserver(forName: Notification.Name.NodesSource.nodesChanged, object: nil, queue: nil) { [weak self] _ in diff --git a/Adamant/Services/DataProviders/AdamantAccountsProvider.swift b/Adamant/Services/DataProviders/AdamantAccountsProvider.swift index 249e5f87d..69b2869e7 100644 --- a/Adamant/Services/DataProviders/AdamantAccountsProvider.swift +++ b/Adamant/Services/DataProviders/AdamantAccountsProvider.swift @@ -9,7 +9,6 @@ import Foundation import CoreData - // MARK: - Provider class AdamantAccountsProvider: AccountsProvider { struct KnownContact { @@ -43,11 +42,9 @@ class AdamantAccountsProvider: AccountsProvider { var apiService: ApiService! var addressBookService: AddressBookService! - // MARK: Properties private let knownContacts: [String:KnownContact] - // MARK: Lifecycle init() { let ico = KnownContact(contact: AdamantContacts.adamantIco) @@ -78,7 +75,7 @@ class AdamantAccountsProvider: AccountsProvider { AdamantContacts.donate.address: donate, AdamantContacts.adamantWelcomeWallet.address: welcome, - AdamantContacts.adamantWelcomeWallet.name: welcome, + AdamantContacts.adamantWelcomeWallet.name: welcome ] NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAddressBookService.addressBookUpdated, object: nil, queue: nil) { [weak self] notification in @@ -130,7 +127,6 @@ class AdamantAccountsProvider: AccountsProvider { } } - // MARK: Threading private let queue = DispatchQueue(label: "im.adamant.accounts.getAccount", qos: .utility, attributes: [.concurrent]) @@ -161,7 +157,7 @@ class AdamantAccountsProvider: AccountsProvider { request.fetchLimit = 1 request.predicate = predicate - var acc: BaseAccount? = nil + var acc: BaseAccount? if let context = context { // viewContext only on MainThread @@ -186,13 +182,12 @@ class AdamantAccountsProvider: AccountsProvider { case let dummy as DummyAccount: return .dummy(dummy) - case .some(_), nil: + case .some, nil: return .notFound } } } - // MARK: - Getting account info from API extension AdamantAccountsProvider { /// Check, if we already have account @@ -213,7 +208,7 @@ extension AdamantAccountsProvider { let account = self.getAccount(byPredicate: NSPredicate(format: "address == %@", address)) switch account { - case .core(_), .dummy(_): completion(true) + case .core, .dummy: completion(true) case .notFound: return completion(false) } } @@ -552,7 +547,6 @@ extension AdamantAccountsProvider { coreAccount.chatroom = chatroom - if let acc = knownContacts[account.address] { coreAccount.name = acc.name coreAccount.avatar = acc.avatar @@ -596,7 +590,6 @@ extension AdamantAccountsProvider { } } - // MARK: - Dummy extension AdamantAccountsProvider { func getDummyAccount(for address: String, completion: @escaping (AccountsProviderDummyAccountResult) -> Void) { diff --git a/Adamant/Services/DataProviders/AdamantChatsProvider+backgroundFetch.swift b/Adamant/Services/DataProviders/AdamantChatsProvider+backgroundFetch.swift index fb8094bb6..4bb2b4efa 100644 --- a/Adamant/Services/DataProviders/AdamantChatsProvider+backgroundFetch.swift +++ b/Adamant/Services/DataProviders/AdamantChatsProvider+backgroundFetch.swift @@ -52,7 +52,7 @@ extension AdamantChatsProvider: BackgroundFetchService { completion(.noData) } - case .failure(_): + case .failure: completion(.failed) } } diff --git a/Adamant/Services/DataProviders/AdamantChatsProvider+fakeMessages.swift b/Adamant/Services/DataProviders/AdamantChatsProvider+fakeMessages.swift index 7c25f7c78..2dbfbcad6 100644 --- a/Adamant/Services/DataProviders/AdamantChatsProvider+fakeMessages.swift +++ b/Adamant/Services/DataProviders/AdamantChatsProvider+fakeMessages.swift @@ -76,7 +76,7 @@ extension AdamantChatsProvider { return } - // MARK 3. Save changes + // MARK: 3. Save changes if privateContext.hasChanges { do { try privateContext.save() @@ -208,10 +208,10 @@ extension AdamantChatsProvider { case .success(let account): completion(.success(loggedAccount: loggedAddress, partner: account)) - case .notFound, .invalidAddress, .notInitiated, .dummy(_): + case .notFound, .invalidAddress, .notInitiated, .dummy: completion(.failure(.accountNotFound(partnerId))) - case .networkError(_): + case .networkError: completion(.failure(.networkError)) case .serverError(let error): @@ -220,7 +220,6 @@ extension AdamantChatsProvider { } } - // MARK: - Tools private func recheckLastTransactionFor(chatroom: Chatroom, with transaction: ChatTransaction) { diff --git a/Adamant/Services/DataProviders/AdamantChatsProvider+search.swift b/Adamant/Services/DataProviders/AdamantChatsProvider+search.swift index f14fae65d..514c1f444 100644 --- a/Adamant/Services/DataProviders/AdamantChatsProvider+search.swift +++ b/Adamant/Services/DataProviders/AdamantChatsProvider+search.swift @@ -10,8 +10,7 @@ import Foundation import CoreData extension AdamantChatsProvider { - func getMessages(containing text: String, in chatroom: Chatroom?) -> [MessageTransaction]? - { + func getMessages(containing text: String, in chatroom: Chatroom?) -> [MessageTransaction]? { let request = NSFetchRequest(entityName: "MessageTransaction") if let chatroom = chatroom { @@ -27,14 +26,13 @@ extension AdamantChatsProvider { NSPredicate(format: "isHidden == false")]) } - request.sortDescriptors = [NSSortDescriptor.init(key: "date", ascending: false), NSSortDescriptor(key: "transactionId", ascending: false)] do { let results = try stack.container.viewContext.fetch(request) return results - } catch let error{ + } catch let error { print(error) } @@ -54,14 +52,13 @@ extension AdamantChatsProvider { NSPredicate(format: "date < %@", date) ]) - request.sortDescriptors = [NSSortDescriptor.init(key: "date", ascending: false), NSSortDescriptor(key: "transactionId", ascending: false)] do { let results = try stack.container.viewContext.fetch(request) return results.count == 0 - } catch let error{ + } catch let error { print(error) return false } diff --git a/Adamant/Services/DataProviders/AdamantChatsProvider.swift b/Adamant/Services/DataProviders/AdamantChatsProvider.swift index 763671e2c..13aafec9e 100644 --- a/Adamant/Services/DataProviders/AdamantChatsProvider.swift +++ b/Adamant/Services/DataProviders/AdamantChatsProvider.swift @@ -43,7 +43,7 @@ class AdamantChatsProvider: ChatsProvider { public var chatLoadedMessages: [String : Int] = [:] private var connection: AdamantConnection? private var isConnectedToTheInthernet = true - private var isRestoredConnectionToTheInthernet: (() ->())? + private var isRestoredConnectionToTheInthernet: (() ->Void)? private(set) var isInitiallySynced: Bool = false { didSet { @@ -123,7 +123,7 @@ class AdamantChatsProvider: ChatsProvider { } } - NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] notification in + NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in if let previousAppState = self?.previousAppState, previousAppState == .background { self?.previousAppState = .active @@ -131,7 +131,7 @@ class AdamantChatsProvider: ChatsProvider { } } - NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] notification in + NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in if self?.isInitiallySynced ?? false { self?.previousAppState = .background } @@ -173,7 +173,7 @@ class AdamantChatsProvider: ChatsProvider { if notify { switch prevState { - case .failedToUpdate(_): + case .failedToUpdate: NotificationCenter.default.post(name: Notification.Name.AdamantTransfersProvider.stateChanged, object: self, userInfo: [AdamantUserInfoKey.TransfersProvider.newState: state, AdamantUserInfoKey.TransfersProvider.prevState: prevState]) @@ -187,7 +187,6 @@ class AdamantChatsProvider: ChatsProvider { } } - // MARK: - DataProvider extension AdamantChatsProvider { func reload() { @@ -236,7 +235,7 @@ extension AdamantChatsProvider { setState(.empty, previous: prevState, notify: notify) } - func getChatRooms(offset: Int?, completion: (() ->())?) { + func getChatRooms(offset: Int?, completion: (() ->Void)?) { guard let address = accountService.account?.address, let privateKey = accountService.keypair?.privateKey else { completion?() @@ -269,7 +268,7 @@ extension AdamantChatsProvider { self?.roomsLoadedCount = chatrooms.chats?.count ?? 0 } - var array = Array() + var array = [Transaction]() chatrooms.chats?.forEach({ room in if let last = room.lastTransaction { array.append(last) @@ -293,7 +292,7 @@ extension AdamantChatsProvider { } } - func apiGetChatrooms(address: String, offset: Int?, completion: ((ChatRooms?) ->())?) { + func apiGetChatrooms(address: String, offset: Int?, completion: ((ChatRooms?) ->Void)?) { apiService.getChatRooms(address: address, offset: offset) { [weak self] result in switch result { case .success(let chatrooms): @@ -319,7 +318,7 @@ extension AdamantChatsProvider { } } - func getChatMessages(with addressRecipient: String, offset: Int?, completion: ((Int) ->())?) { + func getChatMessages(with addressRecipient: String, offset: Int?, completion: ((Int) ->Void)?) { guard let address = accountService.account?.address, let privateKey = accountService.keypair?.privateKey else { completion?(0) @@ -354,7 +353,7 @@ extension AdamantChatsProvider { } } - func apiGetChatMessages(address: String, addressRecipient: String, offset: Int?, completion: ((ChatRooms?) ->())?) { + func apiGetChatMessages(address: String, addressRecipient: String, offset: Int?, completion: ((ChatRooms?) ->Void)?) { apiService.getChatMessages(address: address, addressRecipient: addressRecipient, offset: offset) { [weak self] result in switch result { case .success(let chatroom): @@ -405,7 +404,7 @@ extension AdamantChatsProvider { context: privateContext, contextMutatingSemaphore: cms) } - case .failure(_): + case .failure: break } } @@ -501,13 +500,13 @@ extension AdamantChatsProvider { case .accountNotFound: err = .accountNotFound(address) - case .serverError(_): + case .serverError: err = .serverError(error) case .internalError(let message, _): err = .dependencyError(message) - case .networkError(_): + case .networkError: err = .networkError } @@ -521,7 +520,6 @@ extension AdamantChatsProvider { } } - // MARK: - Sending messages { extension AdamantChatsProvider { func sendMessage(_ message: AdamantMessage, recipientId: String, completion: @escaping (ChatsProviderResultWithTransaction) -> Void) { @@ -670,7 +668,6 @@ extension AdamantChatsProvider { prepareAndSendChatTransaction(transaction, in: context, recipientId: recipientId, type: type, keypair: keypair, from: chatroom, completion: completion) } - /// Transaction must be in passed context private func prepareAndSendChatTransaction(_ transaction: ChatTransaction, in context: NSManagedObjectContext, recipientId: String, type: ChatType, keypair: Keypair, from chatroom: Chatroom? = nil, completion: @escaping (ChatsProviderResultWithTransaction) -> Void) { // MARK: 1. Get account @@ -694,7 +691,7 @@ extension AdamantChatsProvider { completion(.failure(.accountNotFound(recipientId))) return - case .notInitiated(_), .dummy(_): + case .notInitiated, .dummy: completion(.failure(.accountNotInitiated(recipientId))) return @@ -702,7 +699,7 @@ extension AdamantChatsProvider { completion(.failure(.serverError(error))) return - case .networkError(_): + case .networkError: completion(.failure(ChatsProviderError.networkError)) return } @@ -816,7 +813,6 @@ extension AdamantChatsProvider { try? privateContext.save() - // MARK: 3. Send sendTransaction(transaction, type: .message, keypair: keypair, recipientPublicKey: recipientPublicKey) { result in switch result { @@ -863,7 +859,6 @@ extension AdamantChatsProvider { } } - // MARK: - Logic /// Send transaction. @@ -904,7 +899,7 @@ extension AdamantChatsProvider { let serviceError: ChatsProviderError switch error { - case .networkError(_): + case .networkError: serviceError = .networkError case .accountNotFound: @@ -926,7 +921,6 @@ extension AdamantChatsProvider { } } - // MARK: - Getting messages extension AdamantChatsProvider { func getChatroomsController() -> NSFetchedResultsController { @@ -1062,14 +1056,13 @@ extension AdamantChatsProvider { } } - /// - Returns: New unread messagess ids private func process(messageTransactions: [Transaction], senderId: String, privateKey: String, context: NSManagedObjectContext, contextMutatingSemaphore: DispatchSemaphore, - completion: (() -> ())? = nil) { + completion: (() -> Void)? = nil) { struct DirectionedTransaction { let transaction: Transaction let isOut: Bool @@ -1079,7 +1072,6 @@ extension AdamantChatsProvider { let mapped = messageTransactions.map({ DirectionedTransaction(transaction: $0, isOut: $0.senderId == senderId) }) let grouppedTransactions = Dictionary(grouping: mapped, by: { $0.isOut ? $0.transaction.recipientId : $0.transaction.senderId }) - // MARK: 2. Gather Accounts var partners: [CoreDataAccount:[DirectionedTransaction]] = [:] @@ -1288,7 +1280,7 @@ extension AdamantChatsProvider { } } - // MARK 7. Last message height + // MARK: 7. Last message height highSemaphore.wait() if let lastHeight = receivedLastHeight { if lastHeight < height { @@ -1302,7 +1294,6 @@ extension AdamantChatsProvider { } } - // MARK: - Tools extension AdamantChatsProvider { func addUnconfirmed(transactionId id: UInt64, managedObjectId: NSManagedObjectID) { @@ -1382,7 +1373,6 @@ extension AdamantChatsProvider { return nil } - // MARK: Decode message, message must contain data if let decodedMessage = adamantCore.decodeMessage(rawMessage: chat.message, rawNonce: chat.ownMessage, senderPublicKey: publicKey, privateKey: privateKey)?.trimmingCharacters(in: .whitespacesAndNewlines) { if (decodedMessage.isEmpty && transaction.amount > 0) || !decodedMessage.isEmpty { @@ -1461,7 +1451,6 @@ extension AdamantChatsProvider { return messageTransaction } - /// Confirm transactions /// /// - Parameters: diff --git a/Adamant/Services/DataProviders/AdamantTransfersProvider+backgroundFetch.swift b/Adamant/Services/DataProviders/AdamantTransfersProvider+backgroundFetch.swift index c17990b69..2391f9f0c 100644 --- a/Adamant/Services/DataProviders/AdamantTransfersProvider+backgroundFetch.swift +++ b/Adamant/Services/DataProviders/AdamantTransfersProvider+backgroundFetch.swift @@ -54,7 +54,7 @@ extension AdamantTransfersProvider: BackgroundFetchService { completion(.noData) } - case .failure(_): + case .failure: completion(.failed) } } diff --git a/Adamant/Services/DataProviders/AdamantTransfersProvider.swift b/Adamant/Services/DataProviders/AdamantTransfersProvider.swift index 437d05daa..d15bef1f8 100644 --- a/Adamant/Services/DataProviders/AdamantTransfersProvider.swift +++ b/Adamant/Services/DataProviders/AdamantTransfersProvider.swift @@ -48,7 +48,7 @@ class AdamantTransfersProvider: TransfersProvider { if notify { switch prevState { - case .failedToUpdate(_): + case .failedToUpdate: NotificationCenter.default.post(name: Notification.Name.AdamantTransfersProvider.stateChanged, object: nil, userInfo: [AdamantUserInfoKey.TransfersProvider.newState: state, AdamantUserInfoKey.TransfersProvider.prevState: prevState]) @@ -61,7 +61,6 @@ class AdamantTransfersProvider: TransfersProvider { } } - // MARK: Lifecycle init() { NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: nil) { [weak self] notification in @@ -105,7 +104,6 @@ class AdamantTransfersProvider: TransfersProvider { } } - // MARK: - DataProvider extension AdamantTransfersProvider { func reload() { @@ -199,7 +197,6 @@ extension AdamantTransfersProvider { completion?(.success) - case .failedToUpdate(let error): // Processing failed let err: TransfersProviderError @@ -212,13 +209,13 @@ extension AdamantTransfersProvider { case .accountNotFound: err = .accountNotFound(address: address) - case .serverError(_): + case .serverError: err = .serverError(error) case .internalError(let message, _): err = .dependencyError(message: message) - case .networkError(_): + case .networkError: err = .networkError } @@ -268,7 +265,6 @@ extension AdamantTransfersProvider { } } - // MARK: - TransfersProvider extension AdamantTransfersProvider { // MARK: Controllers @@ -346,7 +342,7 @@ extension AdamantTransfersProvider { case .success(let account): recipientAccount = account - case .notFound, .invalidAddress, .notInitiated, .dummy(_): + case .notFound, .invalidAddress, .notInitiated, .dummy: completion(.failure(.accountNotFound(address: recipient))) return @@ -354,7 +350,7 @@ extension AdamantTransfersProvider { completion(.failure(.serverError(error))) return - case .networkError(_): + case .networkError: completion(.failure(.networkError)) return } @@ -467,8 +463,8 @@ extension AdamantTransfersProvider { let accountsGroup = DispatchGroup() accountsGroup.enter() // Enter 1 - var recipientAccount: BaseAccount? = nil - var providerError: TransfersProviderError? = nil + var recipientAccount: BaseAccount? + var providerError: TransfersProviderError? accountsProvider.getAccount(byAddress: recipient) { result in defer { @@ -510,7 +506,7 @@ extension AdamantTransfersProvider { case .serverError(let error): providerError = .serverError(error) - case .networkError(_): + case .networkError: providerError = .networkError } } @@ -530,7 +526,6 @@ extension AdamantTransfersProvider { return } - // MARK: 2. Create transaction let transaction = TransferTransaction(context: context) transaction.amount = amount as NSDecimalNumber @@ -691,7 +686,6 @@ extension AdamantTransfersProvider { } } - // MARK: - Data processing extension AdamantTransfersProvider { private enum ProcessingResult { @@ -800,17 +794,17 @@ extension AdamantTransfersProvider { accountsProvider.getAccount(byAddress: id) { result in switch result { - case .success(_), .dummy(_): + case .success, .dummy: partnersGroup.leave() // Leave 1 - case .notFound, .invalidAddress, .notInitiated(_): + case .notFound, .invalidAddress, .notInitiated: self.accountsProvider.getDummyAccount(for: id) { result in defer { partnersGroup.leave() // Leave 1 } switch result { - case .success(_), .foundRealAccount(_): + case .success, .foundRealAccount: break case .invalidAddress(let address): @@ -926,7 +920,6 @@ extension AdamantTransfersProvider { transfers.append(transfer) } - // MARK: 4. Check lastHeight // API returns transactions from lastHeight INCLUDING transaction with height == lastHeight, so +1 processingHeightSemaphore.wait() diff --git a/Adamant/Services/NativeCore+AdamantCore.swift b/Adamant/Services/NativeCore+AdamantCore.swift index ea0ebe3d2..24dcfe146 100644 --- a/Adamant/Services/NativeCore+AdamantCore.swift +++ b/Adamant/Services/NativeCore+AdamantCore.swift @@ -19,7 +19,6 @@ extension NativeAdamantCore: AdamantCore { return "" } - // MARK: - Signing transactions func sign(transaction: SignableTransaction, senderId: String, keypair: Keypair) -> String? { diff --git a/Adamant/Services/RepeaterService.swift b/Adamant/Services/RepeaterService.swift index 88b7d36f6..e348fced6 100644 --- a/Adamant/Services/RepeaterService.swift +++ b/Adamant/Services/RepeaterService.swift @@ -12,7 +12,7 @@ class RepeaterService { private class Client { let interval: TimeInterval let queue: DispatchQueue? - var timer: Timer? = nil + var timer: Timer? let callback: () -> Void init(interval: TimeInterval, queue: DispatchQueue?, callback: @escaping () -> Void) { diff --git a/Adamant/Services/SocketService/AdamantSocketService.swift b/Adamant/Services/SocketService/AdamantSocketService.swift index f1ead1f1b..04a4719f3 100644 --- a/Adamant/Services/SocketService/AdamantSocketService.swift +++ b/Adamant/Services/SocketService/AdamantSocketService.swift @@ -56,7 +56,7 @@ class AdamantSocketService: SocketService { } func receiveNewTransaction(completion: ((ApiServiceResult) -> Void)?) { - socket?.on("newTrans", callback: { [weak self] data, ack in + socket?.on("newTrans", callback: { [weak self] data, _ in guard let data = data.first else { return } guard let dict = data as? [String: Any] else { return } if let trans = try? JSONDecoder().decode(Transaction.self, from: JSONSerialization.data(withJSONObject: dict)), diff --git a/Adamant/SharedViews/FullscreenAlertView.swift b/Adamant/SharedViews/FullscreenAlertView.swift index a03740226..642c39659 100644 --- a/Adamant/SharedViews/FullscreenAlertView.swift +++ b/Adamant/SharedViews/FullscreenAlertView.swift @@ -39,7 +39,6 @@ class FullscreenAlertView: UIView { } } - // MARK: Lifecycle override func awakeFromNib() { diff --git a/Adamant/SharedViews/TransferCollectionViewCell.swift b/Adamant/SharedViews/TransferCollectionViewCell.swift index 5f6941f82..2a991ab73 100644 --- a/Adamant/SharedViews/TransferCollectionViewCell.swift +++ b/Adamant/SharedViews/TransferCollectionViewCell.swift @@ -48,7 +48,7 @@ class TransferCollectionViewCell: UICollectionViewCell, ChatCell, TapRecognizerT @IBOutlet weak var statusLeadingConstraint: NSLayoutConstraint? @IBOutlet weak var statusTrailingConstraint: NSLayoutConstraint? - weak var delegate: TransferCellDelegate? = nil + weak var delegate: TransferCellDelegate? override func awakeFromNib() { super.awakeFromNib() diff --git a/Adamant/Stories/Account/AccountViewController+StayIn.swift b/Adamant/Stories/Account/AccountViewController+StayIn.swift index 3fff53106..3a331b7f8 100644 --- a/Adamant/Stories/Account/AccountViewController+StayIn.swift +++ b/Adamant/Stories/Account/AccountViewController+StayIn.swift @@ -97,7 +97,6 @@ extension AccountViewController { } } - // MARK: - PinpadViewControllerDelegate extension AccountViewController: PinpadViewControllerDelegate { func pinpad(_ pinpad: PinpadViewController, didEnterPin pin: String) { @@ -110,7 +109,6 @@ extension AccountViewController: PinpadViewControllerDelegate { pinpad.clearPin() return - // MARK: User has reentered pin. Save pin. case .reenterPin(let pinToVerify)?: guard pin == pinToVerify else { @@ -142,7 +140,6 @@ extension AccountViewController: PinpadViewControllerDelegate { } } - // MARK: Users want to turn off the pin. Validate and turn off. case .turnOffPin?: guard accountService.validatePin(pin) else { @@ -155,7 +152,6 @@ extension AccountViewController: PinpadViewControllerDelegate { pinpad.dismiss(animated: true, completion: nil) - // MARK: User wants to turn on biometry case .turnOnBiometry?: guard accountService.validatePin(pin) else { @@ -167,7 +163,6 @@ extension AccountViewController: PinpadViewControllerDelegate { accountService.useBiometry = true pinpad.dismiss(animated: true, completion: nil) - // MARK: User wants to turn off biometry case .turnOffBiometry?: guard accountService.validatePin(pin) else { diff --git a/Adamant/Stories/Account/AccountViewController.swift b/Adamant/Stories/Account/AccountViewController.swift index 2d0ca635f..5eaba9826 100644 --- a/Adamant/Stories/Account/AccountViewController.swift +++ b/Adamant/Stories/Account/AccountViewController.swift @@ -12,7 +12,6 @@ import FreakingSimpleRoundImageView import CoreData import Parchment - // MARK: - Localization extension String.adamantLocalized { struct account { @@ -196,7 +195,6 @@ class AccountViewController: FormViewController { } catch { dialogService.showError(withMessage: "Error fetching transfers: report a bug", error: error) } - // MARK: Header&Footer guard let header = UINib(nibName: "AccountHeader", bundle: nil).instantiate(withOwner: nil, options: nil).first as? AccountHeaderView else { @@ -251,7 +249,7 @@ class AccountViewController: FormViewController { } // Node list - let nodesRow = LabelRow() { + let nodesRow = LabelRow { $0.title = Rows.nodes.localized $0.tag = Rows.nodes.tag $0.cell.imageView?.image = Rows.nodes.image @@ -279,7 +277,7 @@ class AccountViewController: FormViewController { appSection.append(nodesRow) // Currency select - let currencyRow = ActionSheetRow() { + let currencyRow = ActionSheetRow { $0.title = Rows.currency.localized $0.tag = Rows.currency.tag $0.cell.imageView?.image = Rows.currency.image @@ -304,7 +302,7 @@ class AccountViewController: FormViewController { appSection.append(currencyRow) // About - let aboutRow = LabelRow() { + let aboutRow = LabelRow { $0.title = Rows.about.localized $0.tag = Rows.about.tag $0.cell.imageView?.image = Rows.about.image @@ -337,14 +335,14 @@ class AccountViewController: FormViewController { } // Delegates - let delegatesRow = LabelRow() { + let delegatesRow = LabelRow { $0.tag = Rows.voteForDelegates.tag $0.title = Rows.voteForDelegates.localized $0.cell.imageView?.image = Rows.voteForDelegates.image $0.cell.selectionStyle = .gray }.cellUpdate { (cell, _) in cell.accessoryType = .disclosureIndicator - }.onCellSelection { [weak self] (_, row) in + }.onCellSelection { [weak self] (_, _) in guard let vc = self?.router.get(scene: AdamantScene.Delegates.delegates) else { return } @@ -366,7 +364,7 @@ class AccountViewController: FormViewController { actionsSection.append(delegatesRow) // Generate passphrase QR - let generateQrRow = LabelRow() { + let generateQrRow = LabelRow { $0.title = Rows.generateQr.localized $0.tag = Rows.generateQr.tag $0.cell.imageView?.image = Rows.generateQr.image @@ -394,7 +392,7 @@ class AccountViewController: FormViewController { actionsSection.append(generateQrRow) // Generatte private keys - let generatePkRow = LabelRow() { + let generatePkRow = LabelRow { $0.title = Rows.generatePk.localized $0.tag = Rows.generatePk.tag $0.cell.imageView?.image = Rows.generatePk.image @@ -421,9 +419,8 @@ class AccountViewController: FormViewController { actionsSection.append(generatePkRow) - // Logout - let logoutRow = LabelRow() { + let logoutRow = LabelRow { $0.title = Rows.logout.localized $0.tag = Rows.logout.tag $0.cell.imageView?.image = Rows.logout.image @@ -467,7 +464,7 @@ class AccountViewController: FormViewController { // Stay in - let stayInRow = SwitchRow() { + let stayInRow = SwitchRow { $0.tag = Rows.stayIn.tag $0.title = Rows.stayIn.localized $0.cell.imageView?.image = Rows.stayIn.image @@ -485,7 +482,7 @@ class AccountViewController: FormViewController { securitySection.append(stayInRow) // Biometry - let biometryRow = SwitchRow() { [weak self] in + let biometryRow = SwitchRow { [weak self] in $0.tag = Rows.biometry.tag $0.title = localAuth.biometryType.localized $0.value = accountService.useBiometry @@ -515,7 +512,7 @@ class AccountViewController: FormViewController { securitySection.append(biometryRow) // Notifications - let notificationsRow = LabelRow() { [weak self] in + let notificationsRow = LabelRow { [weak self] in $0.tag = Rows.notifications.tag $0.title = Rows.notifications.localized $0.cell.selectionStyle = .gray @@ -558,7 +555,6 @@ class AccountViewController: FormViewController { form.allRows.forEach { $0.baseCell.imageView?.tintColor = UIColor.adamant.tableRowIcons } - // MARK: Notification Center NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.updateAccountInfo() @@ -577,7 +573,7 @@ class AccountViewController: FormViewController { self?.updateAccountInfo() } - NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.stayInChanged, object: nil, queue: OperationQueue.main) { [weak self] notification in + NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.stayInChanged, object: nil, queue: OperationQueue.main) { [weak self] _ in guard let form = self?.form, let accountService = self?.accountService else { return } @@ -692,7 +688,6 @@ class AccountViewController: FormViewController { NotificationCenter.default.removeObserver(self) } - // MARK: TableView configuration override func insertAnimation(forSections sections: [Section]) -> UITableView.RowAnimation { @@ -703,7 +698,6 @@ class AccountViewController: FormViewController { return .fade } - // MARK: Other func updateAccountInfo() { let address: String @@ -740,7 +734,7 @@ class AccountViewController: FormViewController { guard let view = tableView.tableFooterView else { return } view.translatesAutoresizingMaskIntoConstraints = false - let width = view.bounds.size.width; + let width = view.bounds.size.width let temporaryWidthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "[footerView(width)]", options: NSLayoutConstraint.FormatOptions(rawValue: UInt(0)), metrics: ["width": width], views: ["footerView": view]) view.addConstraints(temporaryWidthConstraints) @@ -782,7 +776,6 @@ class AccountViewController: FormViewController { } } - // MARK: - AccountHeaderViewDelegate extension AccountViewController: AccountHeaderViewDelegate { func addressLabelTapped(from: UIView) { @@ -805,7 +798,6 @@ extension AccountViewController: AccountHeaderViewDelegate { } } - // MARK: - NSFetchedResultsControllerDelegate extension AccountViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { @@ -820,7 +812,6 @@ extension AccountViewController: NSFetchedResultsControllerDelegate { } } - // MARK: - PagingViewControllerDataSource extension AccountViewController: PagingViewControllerDataSource, PagingViewControllerDelegate { func numberOfViewControllers(in pagingViewController: PagingViewController) -> Int { diff --git a/Adamant/Stories/Chats/ChatListViewController.swift b/Adamant/Stories/Chats/ChatListViewController.swift index 6d56ef73c..7c406f990 100644 --- a/Adamant/Stories/Chats/ChatListViewController.swift +++ b/Adamant/Stories/Chats/ChatListViewController.swift @@ -87,7 +87,7 @@ class ChatListViewController: UIViewController { private var originalInsets: UIEdgeInsets? private var didShow: Bool = false - var didLoadedMessages: (() ->())? + var didLoadedMessages: (() ->Void)? // MARK: Lifecycle override func viewDidLoad() { @@ -223,7 +223,6 @@ class ChatListViewController: UIViewController { } } - // MARK: Helpers func chatViewController(for chatroom: Chatroom, with message: MessageTransaction? = nil, forceScrollToBottom: Bool = false) -> ChatViewController { guard let vc = router.get(scene: AdamantScene.Chats.chat) as? ChatViewController else { @@ -247,7 +246,6 @@ class ChatListViewController: UIViewController { return vc } - /// - Parameter provider: nil to drop controllers and reset table private func initFetchedRequestControllers(provider: ChatsProvider?) { guard let provider = provider else { @@ -350,7 +348,6 @@ class ChatListViewController: UIViewController { } } - // MARK: - UITableView extension ChatListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -401,7 +398,6 @@ extension ChatListViewController: UITableViewDelegate, UITableViewDataSource { } } - // MARK: - UITableView Cells extension ChatListViewController { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { @@ -548,7 +544,6 @@ extension ChatListViewController { } } - // MARK: - NSFetchedResultsControllerDelegate extension ChatListViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController) { @@ -624,7 +619,6 @@ extension ChatListViewController: NSFetchedResultsControllerDelegate { } } - // MARK: - NewChatViewControllerDelegate extension ChatListViewController: NewChatViewControllerDelegate { func newChatController(_ controller: NewChatViewController, didSelectAccount account: CoreDataAccount, preMessage: String?) { @@ -686,7 +680,6 @@ extension ChatListViewController: NewChatViewControllerDelegate { } } - // MARK: - ChatViewControllerDelegate extension ChatListViewController: ChatViewControllerDelegate { func preserveMessage(_ message: String, forAddress address: String) { @@ -706,7 +699,6 @@ extension ChatListViewController: ChatViewControllerDelegate { } } - // MARK: - Working with in-app notifications extension ChatListViewController { private func showNotification(for transaction: ChatTransaction) { @@ -827,7 +819,6 @@ extension ChatListViewController { } } - // MARK: - Swipe actions extension ChatListViewController { @available(iOS 11.0, *) @@ -862,7 +853,7 @@ extension ChatListViewController { from: view, completion: nil) } else { - let share = UIAlertAction(title: ShareType.share.localized, style: .default) { [weak self] action in + let share = UIAlertAction(title: ShareType.share.localized, style: .default) { [weak self] _ in self?.dialogService.presentShareAlertFor(string: address, types: [.copyToPasteboard, .share, .generateQr(encodedContent: encodedAddress, sharingTip: address, withLogo: true)], excludedActivityTypes: ShareContentType.address.excludedActivityTypes, @@ -870,7 +861,7 @@ extension ChatListViewController { completion: nil) } - let rename = UIAlertAction(title: String.adamantLocalized.chat.rename, style: .default) { [weak self] action in + let rename = UIAlertAction(title: String.adamantLocalized.chat.rename, style: .default) { [weak self] _ in let alert = UIAlertController(title: String(format: String.adamantLocalized.chat.actionsBody, address), message: nil, preferredStyle: .alert) alert.addTextField { (textField) in @@ -925,7 +916,7 @@ extension ChatListViewController { actions = [more] } - let block = UIContextualAction(style: .destructive, title: "Block") { [weak self] (action, view, completionHandler) in + let block = UIContextualAction(style: .destructive, title: "Block") { [weak self] (_, _, completionHandler) in guard let chatroom = self?.chatsController?.object(at: indexPath), let address = chatroom.partner?.address else { completionHandler(false) return @@ -952,7 +943,6 @@ extension ChatListViewController { } } - // MARK: - Tools extension ChatListViewController { /// TabBar item badge diff --git a/Adamant/Stories/Chats/ChatViewController+MessageKit.swift b/Adamant/Stories/Chats/ChatViewController+MessageKit.swift index c887946e3..74c6af290 100644 --- a/Adamant/Stories/Chats/ChatViewController+MessageKit.swift +++ b/Adamant/Stories/Chats/ChatViewController+MessageKit.swift @@ -12,7 +12,6 @@ import MessageInputBar import SafariServices import MarkdownKit - // MARK: - Tools extension ChatViewController { private func getRichMessageType(of message: MessageType) -> String? { @@ -24,7 +23,6 @@ extension ChatViewController { } } - // MARK: - MessagesDataSource extension ChatViewController: MessagesDataSource { func currentSender() -> Sender { @@ -219,7 +217,6 @@ extension ChatViewController: MessagesDataSource { } } - // MARK: - MessagesDisplayDelegate extension ChatViewController: MessagesDisplayDelegate { func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle { @@ -329,7 +326,7 @@ extension ChatViewController: MessageCellDelegate { break } - let retry = UIAlertAction(title: String.adamantLocalized.alert.retry, style: .default, handler: { [weak self] action in + let retry = UIAlertAction(title: String.adamantLocalized.alert.retry, style: .default, handler: { [weak self] _ in self?.chatsProvider.retrySendMessage(message) { result in switch result { case .success: break @@ -337,13 +334,13 @@ extension ChatViewController: MessageCellDelegate { case .failure(let error): self?.dialogService.showRichError(error: error) - case .invalidTransactionStatus(_): + case .invalidTransactionStatus: break } } }) - let cancelMessage = UIAlertAction(title: String.adamantLocalized.alert.delete, style: .default, handler: { [weak self] action in + let cancelMessage = UIAlertAction(title: String.adamantLocalized.alert.delete, style: .default, handler: { [weak self] _ in self?.chatsProvider.cancelMessage(message) { result in switch result { case .success: @@ -351,7 +348,7 @@ extension ChatViewController: MessageCellDelegate { self?.messagesCollectionView.reloadDataAndKeepOffset() } - case .invalidTransactionStatus(_): + case .invalidTransactionStatus: self?.dialogService.showWarning(withMessage: String.adamantLocalized.chat.cancelError) case .failure(let error): @@ -364,7 +361,6 @@ extension ChatViewController: MessageCellDelegate { dialogService?.showAlert(title: String.adamantLocalized.alert.retryOrDeleteTitle, message: String.adamantLocalized.alert.retryOrDeleteBody, style: .actionSheet, actions: [retry, cancelMessage, cancel], from: cell) - // MARK: Show ADM transfer details case let transfer as TransferTransaction: guard let provider = richMessageProviders[AdmWalletService.richMessageType] as? AdmWalletService else { @@ -387,7 +383,6 @@ extension ChatViewController: MessageCellDelegate { provider.richMessageTapped(for: richMessage, at: indexPath, in: self) } - default: break } @@ -584,7 +579,6 @@ extension ChatViewController: MessagesLayoutDelegate { } } - // MARK: - MessageInputBarDelegate extension ChatViewController: MessageInputBarDelegate { private static let markdownParser = MarkdownParser(font: UIFont.systemFont(ofSize: UIFont.systemFontSize)) @@ -623,7 +617,6 @@ extension ChatViewController: MessageInputBarDelegate { DispatchQueue.main.async { self?.scrollDown() } - break case .failure(let error): var showFreeToken = false @@ -696,7 +689,6 @@ extension ChatViewController: MessageInputBarDelegate { } } - // MARK: - MessageType // MARK: MessageTransaction extension MessageTransaction: MessageType { diff --git a/Adamant/Stories/Chats/ChatViewController.swift b/Adamant/Stories/Chats/ChatViewController.swift index 7d676a004..d33ec06aa 100644 --- a/Adamant/Stories/Chats/ChatViewController.swift +++ b/Adamant/Stories/Chats/ChatViewController.swift @@ -44,14 +44,12 @@ extension String.adamantLocalized { } } - // MARK: - Delegate protocol ChatViewControllerDelegate: AnyObject { func preserveMessage(_ message: String, forAddress address: String) func getPreservedMessageFor(address: String, thenRemoveIt: Bool) -> String? } - // MARK: - class ChatViewController: MessagesViewController { // MARK: Dependencies @@ -207,7 +205,7 @@ class ChatViewController: MessagesViewController { private var spinner = UIActivityIndicatorView(style: .whiteLarge) var isBusy = false - //MARK: Background UI + // MARK: Background UI private let amadantLogoImageView: UIImageView = { return UIImageView(image: UIImage(named: "Adamant-logo")) }() @@ -247,7 +245,6 @@ class ChatViewController: MessagesViewController { } } - // MARK: 2. InputBar configuration messageInputBar.delegate = self @@ -655,7 +652,7 @@ class ChatViewController: MessagesViewController { } func close() { - if let tabVC = tabBarController, let selectedView = tabVC.selectedViewController, let nav = selectedView.children.first as? UINavigationController { + if let tabVC = tabBarController, let selectedView = tabVC.selectedViewController, let nav = selectedView.children.first as? UINavigationController { nav.popToRootViewController(animated: true) } else { self.navigationController?.popViewController(animated: true) @@ -705,7 +702,7 @@ class ChatViewController: MessagesViewController { })], from: nil) } - let share = UIAlertAction(title: ShareType.share.localized, style: .default) { [weak self] action in + let share = UIAlertAction(title: ShareType.share.localized, style: .default) { [weak self] _ in self?.dialogService.presentShareAlertFor(string: address, types: [.copyToPasteboard, .share, .generateQr(encodedContent: encodedAddress, sharingTip: address, withLogo: true)], excludedActivityTypes: ShareContentType.address.excludedActivityTypes, @@ -714,7 +711,7 @@ class ChatViewController: MessagesViewController { completion: nil) } - let rename = UIAlertAction(title: String.adamantLocalized.chat.rename, style: .default) { [weak self] action in + let rename = UIAlertAction(title: String.adamantLocalized.chat.rename, style: .default) { [weak self] _ in let alert = UIAlertController(title: String(format: String.adamantLocalized.chat.actionsBody, address), message: nil, preferredStyle: .alert) alert.addTextField { (textField) in @@ -743,7 +740,6 @@ class ChatViewController: MessagesViewController { dialogService?.showAlert(title: nil, message: nil, style: .actionSheet, actions: [block, share, rename, cancel], from: sender) } - // MARK: Tools private func messageKind(for richMessage: RichMessageTransaction) -> MessageKind { guard let type = richMessage.richType else { @@ -772,8 +768,6 @@ class ChatViewController: MessagesViewController { } } - - // MARK: - EstimatedFee label extension ChatViewController { func setEstimatedFee(_ fee: Decimal) { @@ -816,7 +810,6 @@ extension ChatViewController { } } - // MARK: - NSFetchedResultsControllerDelegate extension ChatViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController) { @@ -1122,7 +1115,7 @@ extension ChatViewController { } } -//MARK: Load moore message +// MARK: Load moore message extension ChatViewController { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { loadMooreMessagesIfNeeded(indexPath: indexPath) @@ -1170,7 +1163,7 @@ extension ChatViewController { if address == AdamantContacts.adamantWelcomeWallet.name { return } isBusy = true let offset = chatsProvider.chatLoadedMessages[address] ?? 0 - chatsProvider.getChatMessages(with: address, offset: offset) { [weak self] _count in + chatsProvider.getChatMessages(with: address, offset: offset) { [weak self] _ in DispatchQueue.main.async { self?.messagesCollectionView.reloadDataAndKeepOffset() self?.isBusy = false diff --git a/Adamant/Stories/Chats/ComplexTransferViewController.swift b/Adamant/Stories/Chats/ComplexTransferViewController.swift index e3226886b..5b705ba25 100644 --- a/Adamant/Stories/Chats/ComplexTransferViewController.swift +++ b/Adamant/Stories/Chats/ComplexTransferViewController.swift @@ -18,7 +18,6 @@ class ComplexTransferViewController: UIViewController { var accountService: AccountService! - // MARK: - Properties var pagingViewController: PagingViewController! @@ -45,7 +44,6 @@ class ComplexTransferViewController: UIViewController { // MARK: Services services = accountService.wallets.compactMap { $0 as? WalletServiceWithSend } - // MARK: PagingViewController pagingViewController = PagingViewController() pagingViewController.register(UINib(nibName: "WalletCollectionViewCell", bundle: nil), for: WalletPagingItem.self) diff --git a/Adamant/Stories/Chats/NewChatViewController.swift b/Adamant/Stories/Chats/NewChatViewController.swift index 82dc7ccca..8453d014b 100644 --- a/Adamant/Stories/Chats/NewChatViewController.swift +++ b/Adamant/Stories/Chats/NewChatViewController.swift @@ -32,13 +32,11 @@ extension String.adamantLocalized { } } - // MARK: - Delegate protocol NewChatViewControllerDelegate: AnyObject { func newChatController(_ controller: NewChatViewController, didSelectAccount account: CoreDataAccount, preMessage: String?) } - // MARK: - class NewChatViewController: FormViewController { static let faqUrl = "https://medium.com/adamant-im/chats-and-uninitialized-accounts-in-adamant-5035438e2fcd" @@ -121,7 +119,7 @@ class NewChatViewController: FormViewController { navigationOptions = .Disabled - form +++ Section() { + form +++ Section { $0.footer = { [weak self] in var footer = HeaderFooterView(.callback { let view = ButtonsStripeView.adamantConfigured() @@ -136,7 +134,7 @@ class NewChatViewController: FormViewController { }() } - <<< TextRow() { + <<< TextRow { $0.tag = Rows.addressField.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.keyboardType = .numberPad @@ -150,7 +148,7 @@ class NewChatViewController: FormViewController { view.frame = prefix.frame $0.cell.textField.leftView = view $0.cell.textField.leftViewMode = .always - }.cellUpdate { (cell, row) in + }.cellUpdate { (cell, _) in if let text = cell.textField.text { cell.textField.text = text.components(separatedBy: NewChatViewController.invalidCharacters).joined() } @@ -164,7 +162,7 @@ class NewChatViewController: FormViewController { var trimmed = "" if let admAddress = text.getAdamantAddress() { trimmed = admAddress.address.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() - } else if let admAddress = text.getLegacyAdamantAddress() { + } else if let admAddress = text.getLegacyAdamantAddress() { trimmed = admAddress.address.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() } else { trimmed = text.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() @@ -193,12 +191,12 @@ class NewChatViewController: FormViewController { if let address = accountService.account?.address { let myQrSection = Section() - let button = ButtonRow() { + let button = ButtonRow { $0.tag = Rows.myQr.tag $0.title = Rows.myQr.localized }.cellUpdate { (cell, _) in cell.textLabel?.textColor = UIColor.adamant.primary - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in let encodedAddress = AdamantUriTools.encode(request: AdamantUri.address(address: address, params: nil)) switch AdamantQRTools.generateQrFrom(string: encodedAddress, withLogo: true) { case .success(let qr): @@ -238,7 +236,6 @@ class NewChatViewController: FormViewController { } } - // MARK: - IBActions @IBAction func done(_ sender: Any) { @@ -259,7 +256,6 @@ class NewChatViewController: FormViewController { dismiss(animated: true) } - // MARK: - Other func startNewChat(with address: String, name: String? = nil, message: String?) { @@ -296,7 +292,7 @@ class NewChatViewController: FormViewController { self.dialogService.dismissProgress() } - case .dummy(_): + case .dummy: self.dialogService.dismissProgress() let alert = UIAlertController(title: nil, message: AccountsProviderResult.notInitiated(address: address).localized, preferredStyle: .alert) @@ -320,7 +316,7 @@ class NewChatViewController: FormViewController { self.present(alert, animated: true, completion: nil) } - case .notFound, .invalidAddress, .notInitiated(_), .networkError(_): + case .notFound, .invalidAddress, .notInitiated, .networkError: self.dialogService.showWarning(withMessage: result.localized) case .serverError(let error): @@ -343,7 +339,7 @@ class NewChatViewController: FormViewController { break case .label(label: let label): startNewChat(with: addr, name: label, message: nil) - case .message(_): + case .message: break } } else { @@ -358,7 +354,6 @@ class NewChatViewController: FormViewController { } } - // MARK: - QR extension NewChatViewController { func scanQr() { @@ -442,14 +437,13 @@ extension NewChatViewController { } } - // MARK: - QRCodeReaderViewControllerDelegate extension NewChatViewController: QRCodeReaderViewControllerDelegate { func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { if let admAddress = result.value.getAdamantAddress() { startNewChat(with: admAddress.address, name: admAddress.name, message: admAddress.message) dismiss(animated: true, completion: nil) - } else if let admAddress = result.value.getLegacyAdamantAddress() { + } else if let admAddress = result.value.getLegacyAdamantAddress() { startNewChat(with: admAddress.address, name: admAddress.name, message: admAddress.message) dismiss(animated: true, completion: nil) } else { @@ -465,7 +459,6 @@ extension NewChatViewController: QRCodeReaderViewControllerDelegate { } } - // MARK: - UIImagePickerControllerDelegate extension NewChatViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { @@ -495,7 +488,6 @@ extension NewChatViewController: UINavigationControllerDelegate, UIImagePickerCo } } - // MARK: - ButtonsStripe extension NewChatViewController: ButtonsStripeViewDelegate { func buttonsStripe(_ stripe: ButtonsStripeView, didTapButton button: StripeButtonType) { diff --git a/Adamant/Stories/Chats/SearchResultsViewController.swift b/Adamant/Stories/Chats/SearchResultsViewController.swift index 01470295d..97a567ac3 100644 --- a/Adamant/Stories/Chats/SearchResultsViewController.swift +++ b/Adamant/Stories/Chats/SearchResultsViewController.swift @@ -257,7 +257,7 @@ class SearchResultsViewController: UITableViewController { private func defineSection(for section: Int) -> Section { if self.contacts.count > 0, self.messages.count > 0 { - if section == 0 { + if section == 0 { return .contacts } else { return .messages diff --git a/Adamant/Stories/Delegates/AdamantDelegateCell.swift b/Adamant/Stories/Delegates/AdamantDelegateCell.swift index 55f8c4f8a..c8e62bd2b 100644 --- a/Adamant/Stories/Delegates/AdamantDelegateCell.swift +++ b/Adamant/Stories/Delegates/AdamantDelegateCell.swift @@ -8,7 +8,6 @@ import UIKit - // MARK: Cell's Delegate protocol AdamantDelegateCellDelegate: AnyObject { func delegateCell(_ cell: AdamantDelegateCell, didChangeCheckedStateTo state: Bool) @@ -108,7 +107,6 @@ class AdamantDelegateCell: UITableViewCell { } } - // MARK: Lifecycle override func awakeFromNib() { diff --git a/Adamant/Stories/Delegates/DelegateDetailsViewController.swift b/Adamant/Stories/Delegates/DelegateDetailsViewController.swift index 912dfa53d..bfbf85662 100644 --- a/Adamant/Stories/Delegates/DelegateDetailsViewController.swift +++ b/Adamant/Stories/Delegates/DelegateDetailsViewController.swift @@ -17,7 +17,6 @@ extension String.adamantLocalized { } } - // MARK: - class DelegateDetailsViewController: UIViewController { @@ -105,12 +104,11 @@ class DelegateDetailsViewController: UIViewController { return formatter }() - private var forged: Decimal? = nil - private var forgingTime: TimeInterval? = nil + private var forged: Decimal? + private var forgingTime: TimeInterval? // Double error fix - private var prevApiError: (date: Date, error: ApiServiceError)? = nil - + private var prevApiError: (date: Date, error: ApiServiceError)? // MARK: - Lifecycle @@ -134,7 +132,6 @@ class DelegateDetailsViewController: UIViewController { } } - // MARK: - TableView data & delegate extension DelegateDetailsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -191,7 +188,6 @@ extension DelegateDetailsViewController: UITableViewDelegate, UITableViewDataSou } } - // MARK: - Cells extension DelegateDetailsViewController { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { @@ -266,7 +262,6 @@ extension DelegateDetailsViewController { } } - // MARK: - Tools extension DelegateDetailsViewController { private func refreshData(with delegate: Delegate) { diff --git a/Adamant/Stories/Delegates/DelegatesListViewController.swift b/Adamant/Stories/Delegates/DelegatesListViewController.swift index fc2fa4109..f02243607 100644 --- a/Adamant/Stories/Delegates/DelegatesListViewController.swift +++ b/Adamant/Stories/Delegates/DelegatesListViewController.swift @@ -35,7 +35,6 @@ class DelegatesListViewController: UIViewController { } } - // MARK: - Dependencies var apiService: ApiService! @@ -43,7 +42,6 @@ class DelegatesListViewController: UIViewController { var dialogService: DialogService! var router: Router! - // MARK: - Constants let votingCost: Decimal = Decimal(integerLiteral: 50) @@ -55,7 +53,7 @@ class DelegatesListViewController: UIViewController { // MARK: - Properties private (set) var delegates: [CheckedDelegate] = [CheckedDelegate]() - private var filteredDelegates: [Int]? = nil + private var filteredDelegates: [Int]? private lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() @@ -63,7 +61,7 @@ class DelegatesListViewController: UIViewController { return refreshControl }() - private var forcedUpdateTimer: Timer? = nil + private var forcedUpdateTimer: Timer? private var searchController: UISearchController? @@ -75,7 +73,6 @@ class DelegatesListViewController: UIViewController { // Can start with 'u' or 'U', then 1-20 digits private let possibleAddressRegEx = try! NSRegularExpression(pattern: "^[uU]{0,1}\\d{1,20}$", options: []) - // MARK: - IBOutlets @IBOutlet weak var tableView: UITableView! @@ -212,7 +209,6 @@ class DelegatesListViewController: UIViewController { } } - // MARK: - UITableView extension DelegatesListViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { @@ -267,7 +263,6 @@ extension DelegatesListViewController: UITableViewDataSource, UITableViewDelegat } } - // MARK: - AdamantDelegateCellDelegate extension DelegatesListViewController: AdamantDelegateCellDelegate { func delegateCell(_ cell: AdamantDelegateCell, didChangeCheckedStateTo state: Bool) { @@ -280,7 +275,6 @@ extension DelegatesListViewController: AdamantDelegateCellDelegate { } } - // MARK: - Voting extension DelegatesListViewController { @IBAction func vote(_ sender: Any) { @@ -305,7 +299,6 @@ extension DelegatesListViewController { return } - // MARK: Build request and update UI var votes = [DelegateVote]() @@ -343,15 +336,12 @@ extension DelegatesListViewController { } } - // MARK: - UISearchResultsUpdating extension DelegatesListViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { if let search = searchController.searchBar.text?.lowercased(), search.count > 0 { let searchAddress = possibleAddressRegEx.matches(in: search, options: [], range: NSRange(location: 0, length: search.count)).count == 1 - - let filter: ((Int, CheckedDelegate) -> Bool) if searchAddress { filter = { $1.delegate.username.lowercased().contains(search) || $1.delegate.address.lowercased().contains(search) } @@ -368,7 +358,6 @@ extension DelegatesListViewController: UISearchResultsUpdating { } } - // MARK: - Private extension DelegatesListViewController { private func checkedDelegateFor(indexPath: IndexPath) -> CheckedDelegate { diff --git a/Adamant/Stories/Login/LoginViewController+Pinpad.swift b/Adamant/Stories/Login/LoginViewController+Pinpad.swift index 3ad679a7b..f63779f97 100644 --- a/Adamant/Stories/Login/LoginViewController+Pinpad.swift +++ b/Adamant/Stories/Login/LoginViewController+Pinpad.swift @@ -24,7 +24,6 @@ extension LoginViewController { } } - /// Request user biometry authentication func loginWithBiometry() { let biometry = localAuth.biometryType @@ -89,7 +88,6 @@ extension LoginViewController { } } - // MARK: - PinpadViewControllerDelegate extension LoginViewController: PinpadViewControllerDelegate { func pinpad(_ pinpad: PinpadViewController, didEnterPin pin: String) { diff --git a/Adamant/Stories/Login/LoginViewController+QR.swift b/Adamant/Stories/Login/LoginViewController+QR.swift index 6de266980..c1ac21383 100644 --- a/Adamant/Stories/Login/LoginViewController+QR.swift +++ b/Adamant/Stories/Login/LoginViewController+QR.swift @@ -80,7 +80,6 @@ extension LoginViewController { } } - // MARK: - QRCodeReaderViewControllerDelegate extension LoginViewController: QRCodeReaderViewControllerDelegate { func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { diff --git a/Adamant/Stories/Login/LoginViewController.swift b/Adamant/Stories/Login/LoginViewController.swift index f5b67ea4a..0f171155c 100644 --- a/Adamant/Stories/Login/LoginViewController.swift +++ b/Adamant/Stories/Login/LoginViewController.swift @@ -32,7 +32,6 @@ extension String.adamantLocalized { } } - // MARK: - ViewController class LoginViewController: FormViewController { @@ -117,7 +116,6 @@ class LoginViewController: FormViewController { } } - // MARK: Dependencies var accountService: AccountService! @@ -132,7 +130,6 @@ class LoginViewController: FormViewController { private var firstTimeActive: Bool = true internal var hidingImagePicker: Bool = false - /// On launch, request user biometry (TouchID/FaceID) if has an account with biometry active var requestBiometryOnFirstTimeActive: Bool = true @@ -160,7 +157,6 @@ class LoginViewController: FormViewController { } } - // MARK: Login section form +++ Section(Sections.login.localized) { $0.tag = Sections.login.tag @@ -192,7 +188,7 @@ class LoginViewController: FormViewController { } // Passphrase row - <<< PasswordRow() { + <<< PasswordRow { $0.tag = Rows.passphrase.tag $0.placeholder = Rows.passphrase.localized $0.placeholderColor = UIColor.adamant.secondary @@ -200,7 +196,7 @@ class LoginViewController: FormViewController { } // Login with passphrase row - <<< ButtonRow() { + <<< ButtonRow { $0.tag = Rows.loginButton.tag $0.title = Rows.loginButton.localized $0.disabled = Condition.function([Rows.passphrase.tag], { form -> Bool in @@ -209,7 +205,7 @@ class LoginViewController: FormViewController { } return false }) - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, row) in guard let row: PasswordRow = self?.form.rowBy(tag: Rows.passphrase.tag), let passphrase = row.value else { return } @@ -217,17 +213,16 @@ class LoginViewController: FormViewController { self?.loginWith(passphrase: passphrase) } - // MARK: New account section form +++ Section(Sections.newAccount.localized) { $0.tag = Sections.newAccount.tag } // Alert - <<< TextAreaRow() { + <<< TextAreaRow { $0.tag = Rows.saveYourPassphraseAlert.tag $0.textAreaHeight = .dynamic(initialTextViewHeight: 44) - $0.hidden = Condition.function([], { [weak self] form -> Bool in + $0.hidden = Condition.function([], { [weak self] _ -> Bool in return self?.hideNewPassphrase ?? false }) }.cellUpdate { (cell, _) in @@ -247,14 +242,14 @@ class LoginViewController: FormViewController { } // New genegated passphrase - <<< PassphraseRow() { + <<< PassphraseRow { $0.tag = Rows.newPassphrase.tag $0.cell.tip = Rows.tapToSaveHint.localized $0.cell.height = {96.0} - $0.hidden = Condition.function([], { [weak self] form -> Bool in + $0.hidden = Condition.function([], { [weak self] _ -> Bool in return self?.hideNewPassphrase ?? true }) - }.cellUpdate({ (cell, row) in + }.cellUpdate({ (cell, _) in cell.passphraseLabel.font = UIFont.systemFont(ofSize: 19) cell.passphraseLabel.textColor = UIColor.adamant.primary cell.passphraseLabel.textAlignment = .center @@ -279,16 +274,16 @@ class LoginViewController: FormViewController { completion: nil) }) - <<< ButtonRow() { + <<< ButtonRow { $0.tag = Rows.generateNewPassphraseButton.tag $0.title = Rows.generateNewPassphraseButton.localized - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in self?.generateNewPassphrase() } // MARK: Nodes list settings form +++ Section() - <<< ButtonRow() { + <<< ButtonRow { $0.title = Rows.nodes.localized $0.tag = Rows.nodes.tag }.cellSetup { (cell, _) in @@ -334,7 +329,6 @@ class LoginViewController: FormViewController { } } - // MARK: - Login functions extension LoginViewController { func loginWith(passphrase: String) { @@ -347,10 +341,10 @@ extension LoginViewController { apiService.getAccount(byPassphrase: passphrase) { result in switch result { - case .success(_): + case .success: self.loginIntoExistingAccount(passphrase: passphrase) - case .failure(_): + case .failure: self.createAccountAndLogin(passphrase: passphrase) } } @@ -412,7 +406,6 @@ extension LoginViewController { } } - // MARK: - Button stripe extension LoginViewController: ButtonsStripeViewDelegate { func buttonsStripe(_ stripe: ButtonsStripeView, didTapButton button: StripeButtonType) { diff --git a/Adamant/Stories/NodesEditor/NodeEditorViewController.swift b/Adamant/Stories/NodesEditor/NodeEditorViewController.swift index e0489dcc6..40a02e726 100644 --- a/Adamant/Stories/NodesEditor/NodeEditorViewController.swift +++ b/Adamant/Stories/NodesEditor/NodeEditorViewController.swift @@ -74,12 +74,10 @@ class NodeEditorViewController: FormViewController { } } - // MARK: - Dependencies var dialogService: DialogService! var apiService: ApiService! - // MARK: - Properties var node: Node? var nodeTag: String? @@ -148,7 +146,7 @@ class NodeEditorViewController: FormViewController { form +++ Section() // URL - <<< TextRow() { + <<< TextRow { $0.title = Rows.host.localized $0.tag = Rows.host.tag $0.placeholder = Rows.host.placeholder @@ -159,7 +157,7 @@ class NodeEditorViewController: FormViewController { } // Port - <<< IntRow() { + <<< IntRow { $0.title = Rows.port.localized $0.tag = Rows.port.tag @@ -174,7 +172,7 @@ class NodeEditorViewController: FormViewController { } // Scheme - <<< PickerInlineRow() { + <<< PickerInlineRow { $0.title = Rows.scheme.localized $0.tag = Rows.scheme.tag $0.value = node?.scheme ?? URLScheme.default @@ -200,7 +198,7 @@ class NodeEditorViewController: FormViewController { +++ Section() // Test - <<< LabelRow() { + <<< LabelRow { $0.title = Rows.testButton.localized $0.tag = Rows.testButton.tag }.cellUpdate { (cell, _) in @@ -212,7 +210,7 @@ class NodeEditorViewController: FormViewController { // Delete if node != nil { form +++ Section() - <<< ButtonRow() { + <<< ButtonRow { $0.title = Rows.deleteButton.localized $0.tag = Rows.deleteButton.tag }.onCellSelection { [weak self] (_, _) in @@ -230,7 +228,6 @@ class NodeEditorViewController: FormViewController { } } - // MARK: - Actions extension NodeEditorViewController { private func testNode(completion: ((Bool) -> Void)? = nil) { @@ -278,7 +275,7 @@ extension NodeEditorViewController { private func processApiServiceTestResult(result: ApiServiceResult) -> Bool { switch result { - case .success(_): + case .success: dialogService.dismissProgress() testState = .passed return true diff --git a/Adamant/Stories/NodesEditor/NodesEditorRoutes.swift b/Adamant/Stories/NodesEditor/NodesEditorRoutes.swift index 908c66257..8fe310140 100644 --- a/Adamant/Stories/NodesEditor/NodesEditorRoutes.swift +++ b/Adamant/Stories/NodesEditor/NodesEditorRoutes.swift @@ -30,4 +30,3 @@ extension AdamantScene { private init() {} } } - diff --git a/Adamant/Stories/NodesEditor/NodesListViewController.swift b/Adamant/Stories/NodesEditor/NodesListViewController.swift index 909a6f5a3..d9b67c051 100644 --- a/Adamant/Stories/NodesEditor/NodesListViewController.swift +++ b/Adamant/Stories/NodesEditor/NodesListViewController.swift @@ -9,7 +9,6 @@ import UIKit import Eureka - // MARK: - Localization extension String.adamantLocalized { struct nodesList { @@ -24,7 +23,6 @@ extension String.adamantLocalized { } } - // MARK: - NodesListViewController class NodesListViewController: FormViewController { // Rows & Sections @@ -62,7 +60,6 @@ class NodesListViewController: FormViewController { } } - // MARK: Dependencies var dialogService: DialogService! var securedStore: SecuredStore! @@ -70,13 +67,11 @@ class NodesListViewController: FormViewController { var router: Router! var nodesSource: NodesSource! - // Properties private var nodes = [Node]() private var didResetNodesOnDissapear = false - // MARK: - Lifecycle override func viewDidLoad() { @@ -93,10 +88,9 @@ class NodesListViewController: FormViewController { navigationItem.rightBarButtonItem = done } - // MARK: Nodes - let section = Section() { + let section = Section { $0.tag = Sections.nodes.tag } @@ -105,15 +99,14 @@ class NodesListViewController: FormViewController { form +++ section - // MARK: Buttons - +++ Section() { + +++ Section { $0.tag = Sections.buttons.tag } // Add node - <<< ButtonRow() { + <<< ButtonRow { $0.title = Rows.addNode.localized }.cellSetup { (cell, _) in cell.selectionStyle = .gray @@ -123,11 +116,11 @@ class NodesListViewController: FormViewController { // MARK: Reset - +++ Section() { + +++ Section { $0.tag = Sections.reset.tag } - <<< ButtonRow() { + <<< ButtonRow { $0.title = Rows.reset.localized }.onCellSelection { [weak self] (_, _) in self?.resetToDefault() @@ -165,7 +158,6 @@ class NodesListViewController: FormViewController { */ } - // MARK: - Manipulating node list extension NodesListViewController { func createNewNode() { @@ -230,7 +222,6 @@ extension NodesListViewController { } } - // MARK: - NodeEditorDelegate extension NodesListViewController: NodeEditorDelegate { func nodeEditorViewController(_ editor: NodeEditorViewController, didFinishEditingWithResult result: NodeEditorResult) { @@ -292,7 +283,6 @@ extension NodesListViewController: NodeEditorDelegate { } } - // MARK: - Loading & Saving nodes extension NodesListViewController { func saveNodes() { @@ -315,15 +305,14 @@ extension NodesListViewController { } } - // MARK: - Tools extension NodesListViewController { private func createRowFor(node: Node, tag: String) -> BaseRow { - let row = NodeRow() { + let row = NodeRow { $0.value = node $0.tag = tag - let deleteAction = SwipeAction(style: .destructive, title: "Delete") { [weak self] (action, row, completionHandler) in + let deleteAction = SwipeAction(style: .destructive, title: "Delete") { [weak self] (_, row, completionHandler) in if let node = row.baseValue as? Node, let index = self?.nodes.firstIndex(of: node) { self?.nodes.remove(at: index) self?.saveNodes() diff --git a/Adamant/Stories/Onboard/EulaViewController.swift b/Adamant/Stories/Onboard/EulaViewController.swift index ff1d269a3..8c1f1406c 100644 --- a/Adamant/Stories/Onboard/EulaViewController.swift +++ b/Adamant/Stories/Onboard/EulaViewController.swift @@ -10,8 +10,8 @@ import UIKit class EulaViewController: UIViewController { - var onAccept: (()->Void)? - var onDecline: (()->Void)? + var onAccept: (() -> Void)? + var onDecline: (() -> Void)? override func viewDidLoad() { super.viewDidLoad() diff --git a/Adamant/Stories/Onboard/OnboardRoutes.swift b/Adamant/Stories/Onboard/OnboardRoutes.swift index e6e08638c..e0a64512a 100644 --- a/Adamant/Stories/Onboard/OnboardRoutes.swift +++ b/Adamant/Stories/Onboard/OnboardRoutes.swift @@ -10,12 +10,12 @@ import Foundation extension AdamantScene { struct Onboard { - static let welcome = AdamantScene(identifier: "OnboardViewController") { r in + static let welcome = AdamantScene(identifier: "OnboardViewController") { _ in let c = OnboardViewController(nibName: "OnboardViewController", bundle: nil) return c } - static let eula = AdamantScene(identifier: "EulaViewController") { r in + static let eula = AdamantScene(identifier: "EulaViewController") { _ in let c = EulaViewController(nibName: "EulaViewController", bundle: nil) return c } diff --git a/Adamant/Stories/Onboard/OnboardViewController.swift b/Adamant/Stories/Onboard/OnboardViewController.swift index fe84b633b..ca499174a 100644 --- a/Adamant/Stories/Onboard/OnboardViewController.swift +++ b/Adamant/Stories/Onboard/OnboardViewController.swift @@ -9,7 +9,7 @@ import UIKit import SafariServices -fileprivate class OnboardingPageItem { +private class OnboardingPageItem { var image: UIImage var text: String @@ -36,7 +36,6 @@ class OnboardViewController: UIViewController { private static let buttonsFont = UIFont.adamantPrimary(ofSize: 16, weight: .bold) private static let themeColor = UIColor.adamant.primary - // MARK: Outlets @IBOutlet weak var onboarding: SwiftyOnboard! weak var agreeSwitch: UISwitch? @@ -173,7 +172,6 @@ extension OnboardViewController: SwiftyOnboardDelegate, SwiftyOnboardDataSource } } - // MARK: - UITextViewDelegate extension OnboardViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { diff --git a/Adamant/Stories/Settings/AboutViewController.swift b/Adamant/Stories/Settings/AboutViewController.swift index edc98b74a..08bbadb28 100644 --- a/Adamant/Stories/Settings/AboutViewController.swift +++ b/Adamant/Stories/Settings/AboutViewController.swift @@ -20,7 +20,6 @@ extension String.adamantLocalized { } } - // MARK: - AboutViewController class AboutViewController: FormViewController { // MARK: Section & Rows @@ -113,7 +112,6 @@ class AboutViewController: FormViewController { } } - // MARK: Dependencies var accountService: AccountService! var accountsProvider: AccountsProvider! @@ -123,7 +121,6 @@ class AboutViewController: FormViewController { // MARK: Properties private var storedIOSSupportMessage: String? - // MARK: Lifecycle override func viewDidLoad() { @@ -152,7 +149,6 @@ class AboutViewController: FormViewController { } } - // MARK: About form +++ Section(Sections.about.localized) { $0.tag = Sections.about.tag @@ -187,7 +183,7 @@ class AboutViewController: FormViewController { image: Rows.github.image) // Welcome screens - <<< LabelRow() { + <<< LabelRow { $0.title = Rows.welcomeScreens.localized $0.tag = Rows.welcomeScreens.tag $0.cell.imageView?.image = Rows.welcomeScreens.image @@ -212,7 +208,7 @@ class AboutViewController: FormViewController { } // Adamant - <<< LabelRow() { + <<< LabelRow { $0.title = Rows.adm.localized $0.tag = Rows.adm.tag $0.cell.imageView?.image = Rows.adm.image @@ -249,7 +245,7 @@ class AboutViewController: FormViewController { dialogService?.dismissProgress() } - case .invalidAddress, .notFound, .notInitiated(_), .networkError, .dummy(_): + case .invalidAddress, .notFound, .notInitiated, .networkError, .dummy: dialogService?.showWarning(withMessage: String.adamantLocalized.sharedErrors.networkError) case .serverError(let error): @@ -259,7 +255,7 @@ class AboutViewController: FormViewController { } // E-mail - <<< LabelRow() { + <<< LabelRow { $0.title = Rows.email.localized $0.value = AdamantResources.supportEmail $0.tag = Rows.email.tag @@ -282,7 +278,6 @@ class AboutViewController: FormViewController { mailVC.modalPresentationStyle = .overFullScreen self?.present(mailVC, animated: true, completion: nil) } - /* // Bitcointalk @@ -331,11 +326,10 @@ class AboutViewController: FormViewController { } } - // MARK: - Tools extension AboutViewController { fileprivate func buildUrlRow(title: String, value: String?, tag: String, url urlRaw: String, image: UIImage?) -> LabelRow { - let row = LabelRow() { + let row = LabelRow { $0.tag = tag $0.title = title $0.value = value @@ -359,7 +353,6 @@ extension AboutViewController { } } - // MARK: - MFMailComposeViewControllerDelegate extension AboutViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { @@ -367,7 +360,6 @@ extension AboutViewController: MFMailComposeViewControllerDelegate { } } - // MARK: - ChatViewControllerDelegate extension AboutViewController: ChatViewControllerDelegate { func preserveMessage(_ message: String, forAddress address: String) { diff --git a/Adamant/Stories/Settings/NotificationsViewController.swift b/Adamant/Stories/Settings/NotificationsViewController.swift index 1c71204e9..ae693b082 100644 --- a/Adamant/Stories/Settings/NotificationsViewController.swift +++ b/Adamant/Stories/Settings/NotificationsViewController.swift @@ -79,7 +79,7 @@ class NotificationsViewController: FormViewController { // MARK: Notifications // Type - let nType = ActionSheetRow() { + let nType = ActionSheetRow { $0.tag = Rows.notificationsMode.tag $0.title = Rows.notificationsMode.localized $0.selectorTitle = Rows.notificationsMode.localized @@ -100,10 +100,9 @@ class NotificationsViewController: FormViewController { notificationsSection.append(nType) form.append(notificationsSection) - // MARK: ANS Description // Description - let descriptionRow = TextAreaRow() { + let descriptionRow = TextAreaRow { $0.textAreaHeight = .dynamic(initialTextViewHeight: 44) $0.tag = Rows.description.tag }.cellUpdate { [weak self] (cell, _) in @@ -118,7 +117,7 @@ class NotificationsViewController: FormViewController { } // Github readme - let githubRow = LabelRow() { + let githubRow = LabelRow { $0.tag = Rows.github.tag $0.title = Rows.github.localized $0.cell.imageView?.image = #imageLiteral(resourceName: "row_github") @@ -127,7 +126,7 @@ class NotificationsViewController: FormViewController { cell.selectionStyle = .gray }.cellUpdate { (cell, _) in cell.accessoryType = .disclosureIndicator - }.onCellSelection { [weak self] (_, row) in + }.onCellSelection { [weak self] (_, _) in guard let url = URL(string: AdamantResources.ansReadmeUrl) else { fatalError("Failed to build ANS URL") } @@ -145,7 +144,6 @@ class NotificationsViewController: FormViewController { ansSection.append(contentsOf: [descriptionRow, githubRow]) form.append(ansSection) - // MARK: Notifications NotificationCenter.default.addObserver(forName: Notification.Name.AdamantNotificationService.notificationsModeChanged, object: nil, queue: OperationQueue.main) { [weak self] notification in guard let newMode = notification.userInfo?[AdamantUserInfoKey.NotificationsService.newNotificationsMode] as? NotificationsMode else { diff --git a/Adamant/Stories/Settings/PKGeneratorViewController.swift b/Adamant/Stories/Settings/PKGeneratorViewController.swift index 3467e4bd3..afa84b7e5 100644 --- a/Adamant/Stories/Settings/PKGeneratorViewController.swift +++ b/Adamant/Stories/Settings/PKGeneratorViewController.swift @@ -74,9 +74,9 @@ class PKGeneratorViewController: FormViewController { tableView.showsHorizontalScrollIndicator = false // MARK: PrivateKeys section - let pkSection = Section() { + let pkSection = Section { $0.tag = Sections.privateKeys.tag - $0.hidden = Condition.function([], { [weak self] form -> Bool in + $0.hidden = Condition.function([], { [weak self] _ -> Bool in guard let show = self?.showKeysSection else { return true } @@ -86,9 +86,9 @@ class PKGeneratorViewController: FormViewController { } // MARK: Passphrase section - let passphraseSection = Section() { $0.tag = Sections.passphrase.tag } + let passphraseSection = Section { $0.tag = Sections.passphrase.tag } - let alertRow = TextAreaRow() { + let alertRow = TextAreaRow { $0.tag = Rows.alert.tag $0.textAreaHeight = .dynamic(initialTextViewHeight: 44) }.cellUpdate { (cell, _) in @@ -107,16 +107,16 @@ class PKGeneratorViewController: FormViewController { cell.textView.attributedText = mutableText } - let passphraseRow = TextAreaRow() { + let passphraseRow = TextAreaRow { $0.placeholder = String.adamantLocalized.qrGenerator.passphrasePlaceholder $0.tag = Rows.passphrase.tag $0.textAreaHeight = .dynamic(initialTextViewHeight: 28.0) // 28 for textView and 8+8 for insets } - let generateButton = ButtonRow() { + let generateButton = ButtonRow { $0.title = String.adamantLocalized.pkGenerator.generateButton $0.tag = Rows.generateButton.tag - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, row) in guard let row: TextAreaRow = self?.form.rowBy(tag: Rows.passphrase.tag), let passphrase = row.value else { return } @@ -151,7 +151,7 @@ class PKGeneratorViewController: FormViewController { continue } - let row = LabelRow() { + let row = LabelRow { $0.tag = "row\(index)" index += 1 $0.cell.imageView?.tintColor = UIColor.adamant.tableRowIcons diff --git a/Adamant/Stories/Settings/QRGeneratorViewController.swift b/Adamant/Stories/Settings/QRGeneratorViewController.swift index 747d04d88..483ca5536 100644 --- a/Adamant/Stories/Settings/QRGeneratorViewController.swift +++ b/Adamant/Stories/Settings/QRGeneratorViewController.swift @@ -58,7 +58,6 @@ class QRGeneratorViewController: FormViewController { } } - // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() @@ -74,8 +73,8 @@ class QRGeneratorViewController: FormViewController { tableView.showsHorizontalScrollIndicator = false // MARK: QR section - form +++ Section() { $0.tag = Sections.qr.tag } - <<< QrRow() { + form +++ Section { $0.tag = Sections.qr.tag } + <<< QrRow { $0.tag = Rows.qr.tag $0.cell.tipLabel.text = String.adamantLocalized.qrGenerator.tapToSaveTip }.onCellSelection { [weak self] (cell, row) in @@ -134,17 +133,17 @@ class QRGeneratorViewController: FormViewController { } // MARK: Passphrase section - form +++ Section() { $0.tag = Sections.passphrase.tag } - <<< TextAreaRow() { + form +++ Section { $0.tag = Sections.passphrase.tag } + <<< TextAreaRow { $0.placeholder = String.adamantLocalized.qrGenerator.passphrasePlaceholder $0.tag = Rows.passphrase.tag $0.textAreaHeight = .dynamic(initialTextViewHeight: 28.0) // 28 for textView and 8+8 for insets } - <<< ButtonRow() { + <<< ButtonRow { $0.title = String.adamantLocalized.alert.generateQr $0.tag = Rows.generateButton.tag - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in self?.generateQr() } } @@ -166,7 +165,6 @@ class QRGeneratorViewController: FormViewController { } } - // MARK: - QR Tools extension QRGeneratorViewController { func generateQr() { diff --git a/Adamant/Stories/Settings/SecurityViewController+StayIn.swift b/Adamant/Stories/Settings/SecurityViewController+StayIn.swift index 15385dafc..fb13d3cff 100644 --- a/Adamant/Stories/Settings/SecurityViewController+StayIn.swift +++ b/Adamant/Stories/Settings/SecurityViewController+StayIn.swift @@ -98,7 +98,6 @@ extension SecurityViewController { } } - // MARK: - PinpadViewControllerDelegate extension SecurityViewController: PinpadViewControllerDelegate { func pinpad(_ pinpad: PinpadViewController, didEnterPin pin: String) { @@ -111,7 +110,6 @@ extension SecurityViewController: PinpadViewControllerDelegate { pinpad.clearPin() return - // MARK: User has reentered pin. Save pin. case .reenterPin(let pinToVerify)?: guard pin == pinToVerify else { @@ -147,7 +145,6 @@ extension SecurityViewController: PinpadViewControllerDelegate { } } - // MARK: Users want to turn off the pin. Validate and turn off. case .turnOffPin?: guard accountService.validatePin(pin) else { @@ -160,7 +157,6 @@ extension SecurityViewController: PinpadViewControllerDelegate { pinpad.dismiss(animated: true, completion: nil) - // MARK: User wants to turn on biometry case .turnOnBiometry?: guard accountService.validatePin(pin) else { @@ -172,7 +168,6 @@ extension SecurityViewController: PinpadViewControllerDelegate { accountService.useBiometry = true pinpad.dismiss(animated: true, completion: nil) - // MARK: User wants to turn off biometry case .turnOffBiometry?: guard accountService.validatePin(pin) else { diff --git a/Adamant/Stories/Settings/SecurityViewController.swift b/Adamant/Stories/Settings/SecurityViewController.swift index dcc64d34e..067075681 100644 --- a/Adamant/Stories/Settings/SecurityViewController.swift +++ b/Adamant/Stories/Settings/SecurityViewController.swift @@ -31,7 +31,6 @@ extension NotificationsMode: CustomStringConvertible { } } - // MARK: - SecurityViewController class SecurityViewController: FormViewController { @@ -95,7 +94,6 @@ class SecurityViewController: FormViewController { } } - // MARK: - Dependencies var accountService: AccountService! @@ -104,7 +102,6 @@ class SecurityViewController: FormViewController { var localAuth: LocalAuthentication! var router: Router! - // MARK: - Properties var showLoggedInOptions: Bool { return accountService.hasStayInAccount @@ -122,7 +119,6 @@ class SecurityViewController: FormViewController { var pinpadRequest: SecurityViewController.PinpadRequest? - // MARK: - Lifecycle override func viewDidLoad() { @@ -133,7 +129,7 @@ class SecurityViewController: FormViewController { // MARK: StayIn // Generate QR - let qrRow = LabelRow() { + let qrRow = LabelRow { $0.title = Rows.generateQr.localized $0.tag = Rows.generateQr.tag $0.cell.selectionStyle = .gray @@ -148,7 +144,7 @@ class SecurityViewController: FormViewController { } // Stay logged in - let stayInRow = SwitchRow() { + let stayInRow = SwitchRow { $0.tag = Rows.stayIn.tag $0.title = Rows.stayIn.localized $0.value = accountService.hasStayInAccount @@ -163,7 +159,7 @@ class SecurityViewController: FormViewController { }) // Biometry - let biometryRow = SwitchRow() { + let biometryRow = SwitchRow { $0.tag = Rows.biometry.tag $0.title = localAuth.biometryType.localized $0.value = accountService.useBiometry @@ -189,10 +185,9 @@ class SecurityViewController: FormViewController { stayInSection.append(contentsOf: [qrRow, stayInRow, biometryRow]) form.append(stayInSection) - // MARK: Notifications // Type - let nType = ActionSheetRow() { + let nType = ActionSheetRow { $0.tag = Rows.notificationsMode.tag $0.title = Rows.notificationsMode.localized $0.selectorTitle = Rows.notificationsMode.localized @@ -220,10 +215,9 @@ class SecurityViewController: FormViewController { notificationsSection.append(nType) form.append(notificationsSection) - // MARK: ANS Description // Description - let descriptionRow = TextAreaRow() { + let descriptionRow = TextAreaRow { $0.textAreaHeight = .dynamic(initialTextViewHeight: 44) $0.tag = Rows.description.tag }.cellUpdate { (cell, _) in @@ -235,7 +229,7 @@ class SecurityViewController: FormViewController { } // Github readme - let githubRow = LabelRow() { + let githubRow = LabelRow { $0.tag = Rows.github.tag $0.title = Rows.github.localized $0.cell.imageView?.image = #imageLiteral(resourceName: "row_github") @@ -244,7 +238,7 @@ class SecurityViewController: FormViewController { cell.selectionStyle = .gray }.cellUpdate({ (cell, _) in cell.accessoryType = .disclosureIndicator - }).onCellSelection { [weak self] (_, row) in + }).onCellSelection { [weak self] (_, _) in guard let url = URL(string: AdamantResources.ansReadmeUrl) else { fatalError("Failed to build ANS URL") } @@ -269,13 +263,12 @@ class SecurityViewController: FormViewController { ansSection.append(contentsOf: [descriptionRow, githubRow]) form.append(ansSection) - // MARK: Notifications NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.reloadForm() } - NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.stayInChanged, object: nil, queue: OperationQueue.main) { [weak self] notification in + NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.stayInChanged, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.reloadForm() } diff --git a/Adamant/Stories/Shared/ButtonsStripeView.swift b/Adamant/Stories/Shared/ButtonsStripeView.swift index f699685db..c79628280 100644 --- a/Adamant/Stories/Shared/ButtonsStripeView.swift +++ b/Adamant/Stories/Shared/ButtonsStripeView.swift @@ -54,13 +54,11 @@ extension BiometryType { typealias Stripe = [StripeButtonType] - // MARK: - Delegate protocol ButtonsStripeViewDelegate: AnyObject { func buttonsStripe(_ stripe: ButtonsStripeView, didTapButton button: StripeButtonType) } - // MARK: - View class ButtonsStripeView: UIView { // MARK: IBOutlet @@ -68,9 +66,9 @@ class ButtonsStripeView: UIView { // MARK: Properties weak var delegate: ButtonsStripeViewDelegate? - private var buttons: [RoundedButton]? = nil + private var buttons: [RoundedButton]? - var stripe: Stripe? = nil { + var stripe: Stripe? { didSet { for aView in stripeStackView.subviews { aView.removeFromSuperview() @@ -113,7 +111,7 @@ class ButtonsStripeView: UIView { } // MARK: Buttons properties - var buttonsBorderColor: UIColor? = nil { + var buttonsBorderColor: UIColor? { didSet { if let buttons = buttons { buttons.forEach { $0.borderColor = buttonsBorderColor } @@ -137,7 +135,7 @@ class ButtonsStripeView: UIView { } } - var buttonsNormalColor: UIColor? = nil { + var buttonsNormalColor: UIColor? { didSet { if let buttons = buttons { buttons.forEach { $0.normalBackgroundColor = buttonsNormalColor } @@ -145,7 +143,7 @@ class ButtonsStripeView: UIView { } } - var buttonsHighlightedColor: UIColor? = nil { + var buttonsHighlightedColor: UIColor? { didSet { if let buttons = buttons { buttons.forEach { $0.highlightedBackgroundColor = buttonsHighlightedColor } @@ -167,7 +165,6 @@ class ButtonsStripeView: UIView { } } - // MARK: Adamant config extension ButtonsStripeView { static let adamantDefaultHeight: CGFloat = 85 diff --git a/Adamant/Stories/Shared/ShareQrViewController.swift b/Adamant/Stories/Shared/ShareQrViewController.swift index b0a1c5f58..e3dc5da10 100644 --- a/Adamant/Stories/Shared/ShareQrViewController.swift +++ b/Adamant/Stories/Shared/ShareQrViewController.swift @@ -18,7 +18,6 @@ class ShareQrViewController: FormViewController { // MARK: - Dependencies var dialogService: DialogService! - // MARK: - Rows private enum Rows { case qr @@ -86,7 +85,7 @@ class ShareQrViewController: FormViewController { // MARK: QR code let qrSection = Section() - let qrRow = QrRow() { + let qrRow = QrRow { $0.value = qrCode $0.tag = Rows.qr.tag $0.cell.selectionStyle = .none @@ -108,10 +107,10 @@ class ShareQrViewController: FormViewController { let buttonsSection = Section() // Photolibrary - let photolibraryRow = ButtonRow() { + let photolibraryRow = ButtonRow { $0.tag = Rows.saveToPhotos.tag $0.title = Rows.saveToPhotos.localized - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, row) in guard let row: QrRow = self?.form.rowBy(tag: Rows.qr.tag), let qrCode = row.value else { return } @@ -131,7 +130,7 @@ class ShareQrViewController: FormViewController { } // Share - let shareRow = ButtonRow() { + let shareRow = ButtonRow { $0.tag = Rows.shareButton.tag $0.title = Rows.shareButton.localized }.onCellSelection { [weak self] (cell, row) in @@ -149,7 +148,7 @@ class ShareQrViewController: FormViewController { c.sourceRect = cell.bounds } - vc.completionWithItemsHandler = { [weak self] (type: UIActivity.ActivityType?, completed: Bool, _, error: Error?) in + vc.completionWithItemsHandler = { [weak self] (_: UIActivity.ActivityType?, completed: Bool, _, error: Error?) in if completed { if let error = error { self?.dialogService.showWarning(withMessage: error.localizedDescription) @@ -163,10 +162,10 @@ class ShareQrViewController: FormViewController { self?.present(vc, animated: true, completion: nil) } - let cancelRow = ButtonRow() { + let cancelRow = ButtonRow { $0.tag = Rows.cancelButton.tag $0.title = Rows.cancelButton.localized - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in self?.close() } diff --git a/Adamant/Stories/SwiftyOnboard/SwiftyOnboard.swift b/Adamant/Stories/SwiftyOnboard/SwiftyOnboard.swift index b13584e59..ac5bbc845 100644 --- a/Adamant/Stories/SwiftyOnboard/SwiftyOnboard.swift +++ b/Adamant/Stories/SwiftyOnboard/SwiftyOnboard.swift @@ -21,7 +21,7 @@ public protocol SwiftyOnboardDataSource: AnyObject { public extension SwiftyOnboardDataSource { - func swiftyOnboardBackgroundColorFor(_ swiftyOnboard: SwiftyOnboard,atIndex index: Int)->UIColor?{ + func swiftyOnboardBackgroundColorFor(_ swiftyOnboard: SwiftyOnboard,atIndex index: Int) -> UIColor? { return nil } @@ -54,7 +54,7 @@ public class SwiftyOnboard: UIView, UIScrollViewDelegate { open weak var dataSource: SwiftyOnboardDataSource? { didSet { - if let color = dataSource?.swiftyOnboardBackgroundColorFor(self, atIndex: 0){ + if let color = dataSource?.swiftyOnboardBackgroundColorFor(self, atIndex: 0) { backgroundColor = color } dataSourceSet = true @@ -84,7 +84,6 @@ public class SwiftyOnboard: UIView, UIScrollViewDelegate { open var shouldSwipe: Bool = true open var fadePages: Bool = true - public init(frame: CGRect, style: SwiftyOnboardStyle = .dark) { super.init(frame: frame) self.style = style @@ -130,7 +129,7 @@ public class SwiftyOnboard: UIView, UIScrollViewDelegate { fileprivate func setUpPages() { if let dataSource = dataSource { pageCount = dataSource.swiftyOnboardNumberOfPages(self) - for index in 0..UIColor?{ + fileprivate func colorForPosition(_ pos: CGFloat) -> UIColor? { let percentage: CGFloat = pos - CGFloat(Int(pos)) let currentIndex = Int(pos - percentage) - if currentIndex < pageCount - 1{ + if currentIndex < pageCount - 1 { let color1 = dataSource?.swiftyOnboardBackgroundColorFor(self, atIndex: currentIndex) let color2 = dataSource?.swiftyOnboardBackgroundColorFor(self, atIndex: currentIndex + 1) if let color1 = color1, - let color2 = color2{ + let color2 = color2 { return colorFrom(start: color1, end: color2, percent: percentage) } } return nil } - fileprivate func colorFrom(start color1: UIColor, end color2: UIColor, percent: CGFloat)->UIColor{ - func cofd(_ color1: CGFloat,_ color2: CGFloat,_ percent: CGFloat)-> CGFloat{ + fileprivate func colorFrom(start color1: UIColor, end color2: UIColor, percent: CGFloat) -> UIColor { + func cofd(_ color1: CGFloat,_ color2: CGFloat,_ percent: CGFloat) -> CGFloat { let c1 = CGFloat(color1) let c2 = CGFloat(color2) return (c1 + ((c2 - c1) * percent)) @@ -219,7 +218,7 @@ public class SwiftyOnboard: UIView, UIScrollViewDelegate { self.goToPage(index: page, animated: true) } - open var currentPage: Int{ + open var currentPage: Int { return Int(getCurrentPosition()) } diff --git a/Adamant/SwinjectDependencies.swift b/Adamant/SwinjectDependencies.swift index d2c96968d..c8f6f611d 100644 --- a/Adamant/SwinjectDependencies.swift +++ b/Adamant/SwinjectDependencies.swift @@ -8,7 +8,6 @@ import Swinject - // MARK: - Services extension Container { func registerAdamantServices() { @@ -27,16 +26,16 @@ extension Container { self.register(CellFactory.self) { _ in AdamantCellFactory() }.inObjectScope(.container) // MARK: Secured Store - self.register(SecuredStore.self) { r in KeychainStore() }.inObjectScope(.container) + self.register(SecuredStore.self) { _ in KeychainStore() }.inObjectScope(.container) // MARK: LocalAuthentication - self.register(LocalAuthentication.self) { r in AdamantAuthentication() }.inObjectScope(.container) + self.register(LocalAuthentication.self) { _ in AdamantAuthentication() }.inObjectScope(.container) // MARK: Reachability - self.register(ReachabilityMonitor.self) { r in AdamantReachability() }.inObjectScope(.container) + self.register(ReachabilityMonitor.self) { _ in AdamantReachability() }.inObjectScope(.container) // MARK: AdamantAvatarService - self.register(AvatarService.self) { r in AdamantAvatarService() }.inObjectScope(.container) + self.register(AvatarService.self) { _ in AdamantAvatarService() }.inObjectScope(.container) // MARK: - Services with dependencies // MARK: DialogService @@ -177,7 +176,7 @@ extension Container { func registerAdamantBackgroundFetchServices() { // MARK: Secured store - self.register(SecuredStore.self) { r in KeychainStore() }.inObjectScope(.container) + self.register(SecuredStore.self) { _ in KeychainStore() }.inObjectScope(.container) // MARK: NodesSource self.register(NodesSource.self) { r in diff --git a/Adamant/Utilities/AdamantUtilities+extended.swift b/Adamant/Utilities/AdamantUtilities+extended.swift index e88870a03..d1e5b5c47 100644 --- a/Adamant/Utilities/AdamantUtilities+extended.swift +++ b/Adamant/Utilities/AdamantUtilities+extended.swift @@ -34,7 +34,6 @@ extension AdamantUtilities { } } - // MARK: - Validating Addresses and Passphrases extension AdamantUtilities { static let addressRegexString = "^U([0-9]{6,20})$" @@ -93,7 +92,6 @@ extension AdamantUtilities { } } - // MARK: - Hex extension AdamantUtilities { static func getHexString(from bytes: [UInt8]) -> String { diff --git a/Adamant/Utilities/ByteBackpacker.swift b/Adamant/Utilities/ByteBackpacker.swift index d17e2ff77..cf1e5914c 100644 --- a/Adamant/Utilities/ByteBackpacker.swift +++ b/Adamant/Utilities/ByteBackpacker.swift @@ -4,10 +4,8 @@ This file is part of ByteBackpacker Project. It is subject to the license terms import Foundation - public typealias Byte = UInt8 - /// ByteOrder /// /// Byte order can be either big or little endian. @@ -19,7 +17,6 @@ public enum ByteOrder { public static let nativeByteOrder: ByteOrder = (Int(CFByteOrderGetCurrent()) == Int(CFByteOrderLittleEndian.rawValue)) ? .littleEndian : .bigEndian } - open class ByteBackpacker { private static let referenceTypeErrorString = "TypeError: Reference Types are not supported." @@ -34,7 +31,6 @@ open class ByteBackpacker { return ByteBackpacker.unpack(valueByteArray, toType: T.self, byteOrder: byteOrder) } - /// Unpack a byte array into type `T` for type inference /// /// - Parameters: @@ -52,7 +48,6 @@ open class ByteBackpacker { } } - /// Pack method convinience method /// /// - Parameters: @@ -63,13 +58,12 @@ open class ByteBackpacker { assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString) var value = value // inout works only for var not let types let valueByteArray = withUnsafePointer(to: &value) { - Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: Byte.self, capacity: 1){$0}, count: MemoryLayout.size)) + Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: Byte.self, capacity: 1) {$0}, count: MemoryLayout.size)) } return (byteOrder == ByteOrder.nativeByteOrder) ? valueByteArray : valueByteArray.reversed() } } - public extension Data { /// Extension for exporting Data (NSData) to byte array directly @@ -82,5 +76,3 @@ public extension Data { return array } } - - diff --git a/Adamant/Utilities/KeyboardManager.swift b/Adamant/Utilities/KeyboardManager.swift index ed01feb63..3eb0efe9b 100644 --- a/Adamant/Utilities/KeyboardManager.swift +++ b/Adamant/Utilities/KeyboardManager.swift @@ -31,7 +31,7 @@ import UIKit open class KeyboardManager: NSObject, UIGestureRecognizerDelegate { /// A callback that passes a `KeyboardNotification` as an input - public typealias EventCallback = (KeyboardNotification)->Void + public typealias EventCallback = (KeyboardNotification) -> Void // MARK: - Properties [Public] @@ -258,7 +258,7 @@ open class KeyboardManager: NSObject, UIGestureRecognizerDelegate { // MARK: - Helper Methods - private func animateAlongside(_ notification: KeyboardNotification, animations: @escaping ()->Void) { + private func animateAlongside(_ notification: KeyboardNotification, animations: @escaping () -> Void) { UIView.animate(withDuration: notification.timeInterval, delay: 0, options: [notification.animationOptions, .allowAnimatedContent, .beginFromCurrentState], animations: animations, completion: nil) } @@ -502,7 +502,6 @@ class NSLayoutConstraintSet { } } - // // NSNotification+Extensions.swift // InputBarAccessoryView @@ -593,4 +592,3 @@ internal extension NSNotification { } } - diff --git a/Adamant/Wallets/Adamant/AdmTransactionDetailsViewController.swift b/Adamant/Wallets/Adamant/AdmTransactionDetailsViewController.swift index 33646a2ed..dfb634c3a 100644 --- a/Adamant/Wallets/Adamant/AdmTransactionDetailsViewController.swift +++ b/Adamant/Wallets/Adamant/AdmTransactionDetailsViewController.swift @@ -33,8 +33,8 @@ class AdmTransactionDetailsViewController: TransactionDetailsViewControllerBase if showToChat { let haveChatroom: Bool - if let transfer = transaction as? TransferTransaction, let partner = transfer.partner as? CoreDataAccount, let chatroom = partner.chatroom, let transactions = chatroom.transactions { - let messeges = transactions.first (where: { (object) -> Bool in + if let transfer = transaction as? TransferTransaction, let partner = transfer.partner as? CoreDataAccount, let chatroom = partner.chatroom, let transactions = chatroom.transactions { + let messeges = transactions.first(where: { (object) -> Bool in return !(object is TransferTransaction) }) @@ -47,7 +47,7 @@ class AdmTransactionDetailsViewController: TransactionDetailsViewControllerBase // MARK: Open chat if let trs = transaction as? TransferTransaction, trs.chatroom != nil, let section = form.sectionBy(tag: Sections.actions.tag) { - let row = LabelRow() { + let row = LabelRow { $0.tag = Rows.openChat.tag $0.title = chatLabel $0.cell.imageView?.image = Rows.openChat.image diff --git a/Adamant/Wallets/Adamant/AdmTransactionsViewController.swift b/Adamant/Wallets/Adamant/AdmTransactionsViewController.swift index 55d54b12d..869026a95 100644 --- a/Adamant/Wallets/Adamant/AdmTransactionsViewController.swift +++ b/Adamant/Wallets/Adamant/AdmTransactionsViewController.swift @@ -117,7 +117,6 @@ class AdmTransactionsViewController: TransactionsListViewControllerBase { } } } - // MARK: - UITableView @@ -198,13 +197,13 @@ class AdmTransactionsViewController: TransactionsListViewControllerBase { return nil } - let messeges = transactions.first (where: { (object) -> Bool in + let messeges = transactions.first(where: { (object) -> Bool in return !(object is TransferTransaction) }) let title = (messeges != nil) ? String.adamantLocalized.transactionList.toChat : String.adamantLocalized.transactionList.startChat - let toChat = UITableViewRowAction(style: .normal, title: title) { action, index in + let toChat = UITableViewRowAction(style: .normal, title: title) { _, _ in guard let vc = self.router.get(scene: AdamantScene.Chats.chat) as? ChatViewController else { // TODO: Log this return @@ -245,7 +244,7 @@ class AdmTransactionsViewController: TransactionsListViewControllerBase { return nil } - let messeges = transactions.first (where: { (object) -> Bool in + let messeges = transactions.first(where: { (object) -> Bool in return !(object is TransferTransaction) }) diff --git a/Adamant/Wallets/Adamant/AdmTransferViewController.swift b/Adamant/Wallets/Adamant/AdmTransferViewController.swift index 90fe70116..4c7d7e5e8 100644 --- a/Adamant/Wallets/Adamant/AdmTransferViewController.swift +++ b/Adamant/Wallets/Adamant/AdmTransferViewController.swift @@ -49,10 +49,10 @@ class AdmTransferViewController: TransferViewControllerBase { // Check recipient accountsProvider.getAccount(byAddress: recipient) { result in switch result { - case .success(_): + case .success: self.sendFundsInternal(service: service, recipient: recipient, amount: amount, comments: comments) - case .notFound(_), .notInitiated(_), .dummy(_): + case .notFound, .notInitiated, .dummy: let alert = UIAlertController(title: String.adamantLocalized.transferAdm.accountNotFoundAlertTitle(for: recipient), message: String.adamantLocalized.transferAdm.accountNotFoundAlertBody, preferredStyle: .alert) @@ -85,7 +85,7 @@ class AdmTransferViewController: TransferViewControllerBase { self.dialogService.dismissProgress() } - case .invalidAddress(_), .serverError(_), .networkError(_): + case .invalidAddress, .serverError, .networkError: self.dialogService.showWarning(withMessage: result.localized) } } @@ -143,7 +143,6 @@ class AdmTransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -167,7 +166,7 @@ class AdmTransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = TextRow() { + let row = TextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.keyboardType = .numberPad @@ -191,7 +190,7 @@ class AdmTransferViewController: TransferViewControllerBase { $0.disabled = true // prefix.isEnabled = false } - }.cellUpdate { (cell, row) in + }.cellUpdate { (cell, _) in if let text = cell.textField.text { cell.textField.text = text.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() } @@ -205,7 +204,7 @@ class AdmTransferViewController: TransferViewControllerBase { var trimmed = "" if let admAddress = text.getAdamantAddress() { trimmed = admAddress.address.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() - } else if let admAddress = text.getLegacyAdamantAddress() { + } else if let admAddress = text.getLegacyAdamantAddress() { trimmed = admAddress.address.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() } else { trimmed = text.components(separatedBy: AdmTransferViewController.invalidCharactersSet).joined() @@ -222,7 +221,7 @@ class AdmTransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/Adamant/AdmWalletService+Send.swift b/Adamant/Wallets/Adamant/AdmWalletService+Send.swift index 9e0fdeb81..098eba9a4 100644 --- a/Adamant/Wallets/Adamant/AdmWalletService+Send.swift +++ b/Adamant/Wallets/Adamant/AdmWalletService+Send.swift @@ -21,7 +21,6 @@ extension AdmWalletService: WalletServiceSimpleSend { return vc } - func sendMoney(recipient: String, amount: Decimal, comments: String, completion: @escaping (WalletServiceResult) -> Void) { transfersProvider.transferFunds(toAddress: recipient, amount: amount, comment: comments) { result in switch result { diff --git a/Adamant/Wallets/Adamant/AdmWalletService.swift b/Adamant/Wallets/Adamant/AdmWalletService.swift index 7aa900bfc..c4d3b05db 100644 --- a/Adamant/Wallets/Adamant/AdmWalletService.swift +++ b/Adamant/Wallets/Adamant/AdmWalletService.swift @@ -39,7 +39,6 @@ class AdmWalletService: NSObject, WalletService { var transfersProvider: TransfersProvider! var router: Router! - // MARK: - Notifications let walletUpdatedNotification = Notification.Name("adamant.admWallet.updated") let serviceEnabledChanged = Notification.Name("adamant.admWallet.enabledChanged") @@ -68,8 +67,7 @@ class AdmWalletService: NSObject, WalletService { // MARK: - State private (set) var state: WalletServiceState = .upToDate - private (set) var wallet: WalletAccount? = nil - + private (set) var wallet: WalletAccount? // MARK: - Logic override init() { @@ -116,7 +114,6 @@ class AdmWalletService: NSObject, WalletService { } } - // MARK: - Tools func validate(address: String) -> AddressValidationResult { guard !AdamantContacts.systemAddresses.contains(address) else { @@ -141,7 +138,6 @@ extension AdmWalletService: WalletServiceWithTransfers { } } - // MARK: - NSFetchedResultsControllerDelegate extension AdmWalletService: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { @@ -156,7 +152,6 @@ extension AdmWalletService: NSFetchedResultsControllerDelegate { } } - // MARK: - Dependencies extension AdmWalletService: SwinjectDependentService { func injectDependencies(from container: Container) { diff --git a/Adamant/Wallets/Adamant/AdmWalletViewController.swift b/Adamant/Wallets/Adamant/AdmWalletViewController.swift index b002f1659..c5db194e4 100644 --- a/Adamant/Wallets/Adamant/AdmWalletViewController.swift +++ b/Adamant/Wallets/Adamant/AdmWalletViewController.swift @@ -83,7 +83,7 @@ class AdmWalletViewController: WalletViewControllerBase { // MARK: Rows - let buyTokensRow = LabelRow() { + let buyTokensRow = LabelRow { $0.tag = Rows.buyTokens.tag $0.title = Rows.buyTokens.localized $0.cell.imageView?.image = Rows.buyTokens.image @@ -109,7 +109,7 @@ class AdmWalletViewController: WalletViewControllerBase { } } - let freeTokensRow = LabelRow() { + let freeTokensRow = LabelRow { $0.tag = Rows.freeTokens.tag $0.title = Rows.freeTokens.localized $0.cell.imageView?.image = Rows.freeTokens.image @@ -163,7 +163,7 @@ class AdmWalletViewController: WalletViewControllerBase { } override func adressRow() -> LabelRow { - let addressRow = LabelRow() { + let addressRow = LabelRow { $0.tag = BaseRows.address.tag $0.title = BaseRows.address.localized $0.cell.selectionStyle = .gray diff --git a/Adamant/Wallets/Adamant/BuyAndSellViewController.swift b/Adamant/Wallets/Adamant/BuyAndSellViewController.swift index 9041e7ce1..ac6fb1efb 100644 --- a/Adamant/Wallets/Adamant/BuyAndSellViewController.swift +++ b/Adamant/Wallets/Adamant/BuyAndSellViewController.swift @@ -97,7 +97,7 @@ class BuyAndSellViewController: FormViewController { } private func buildUrlRow(title: String, value: String?, tag: String, urlRaw: String, image: UIImage?) -> LabelRow { - let row = LabelRow() { + let row = LabelRow { $0.tag = tag $0.title = title $0.value = value diff --git a/Adamant/Wallets/BalanceTableViewCell.swift b/Adamant/Wallets/BalanceTableViewCell.swift index 3ca19831b..d0d70b87b 100644 --- a/Adamant/Wallets/BalanceTableViewCell.swift +++ b/Adamant/Wallets/BalanceTableViewCell.swift @@ -91,7 +91,6 @@ public final class BalanceTableViewCell: Cell, CellType { } } - // MARK: - Row public final class BalanceRow: Row, RowType { var alertBackgroundColor: UIColor? diff --git a/Adamant/Wallets/Dash/DashTransactionDetailsViewController.swift b/Adamant/Wallets/Dash/DashTransactionDetailsViewController.swift index 4ef75bab0..f57b4bff5 100644 --- a/Adamant/Wallets/Dash/DashTransactionDetailsViewController.swift +++ b/Adamant/Wallets/Dash/DashTransactionDetailsViewController.swift @@ -16,7 +16,7 @@ class DashTransactionDetailsViewController: TransactionDetailsViewControllerBase // MARK: - Properties - private var cachedBlockInfo: (hash: String, height: String)? = nil + private var cachedBlockInfo: (hash: String, height: String)? private let autoupdateInterval: TimeInterval = 5.0 weak var timer: Timer? diff --git a/Adamant/Wallets/Dash/DashTransactionsViewController.swift b/Adamant/Wallets/Dash/DashTransactionsViewController.swift index c3d051d95..fcff71082 100644 --- a/Adamant/Wallets/Dash/DashTransactionsViewController.swift +++ b/Adamant/Wallets/Dash/DashTransactionsViewController.swift @@ -184,7 +184,7 @@ class DashTransactionsViewController: TransactionsListViewControllerBase { private func loadMoreTransactions() { let procedure = LoadMoreDashTransactionsProcedure(service: walletService) - procedure.addDidFinishBlockObserver { [weak self] (procedure, error) in + procedure.addDidFinishBlockObserver { [weak self] (procedure, _) in guard let vc = self, let result = procedure.result else { return } @@ -214,11 +214,10 @@ class DashTransactionsViewController: TransactionsListViewControllerBase { } } - private class LoadMoreDashTransactionsProcedure: Procedure { let service: DashWalletService - private(set) var result: DashTransactionsPointer? = nil + private(set) var result: DashTransactionsPointer? init(service: DashWalletService) { self.service = service diff --git a/Adamant/Wallets/Dash/DashTransferViewController.swift b/Adamant/Wallets/Dash/DashTransferViewController.swift index 835e78e4a..5f28b79d6 100644 --- a/Adamant/Wallets/Dash/DashTransferViewController.swift +++ b/Adamant/Wallets/Dash/DashTransferViewController.swift @@ -19,14 +19,12 @@ class DashTransferViewController: TransferViewControllerBase { var chatsProvider: ChatsProvider! - // MARK: Properties private var skipValueChange: Bool = false static let invalidCharacters: CharacterSet = CharacterSet.decimalDigits.inverted - // MARK: Send override func sendFunds() { @@ -144,7 +142,6 @@ class DashTransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -178,7 +175,7 @@ class DashTransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = TextRow() { + let row = TextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.autocorrectionType = .no @@ -202,7 +199,7 @@ class DashTransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/Dash/DashWalletService+Send.swift b/Adamant/Wallets/Dash/DashWalletService+Send.swift index 56216b231..53465444a 100644 --- a/Adamant/Wallets/Dash/DashWalletService+Send.swift +++ b/Adamant/Wallets/Dash/DashWalletService+Send.swift @@ -23,7 +23,6 @@ extension DashWalletService: WalletServiceTwoStepSend { return vc } - // MARK: Create & Send func create(recipient: String, amount: Decimal, completion: @escaping (WalletServiceResult) -> Void) { if let lastTransaction = self.lastTransactionId { diff --git a/Adamant/Wallets/Dash/DashWalletService.swift b/Adamant/Wallets/Dash/DashWalletService.swift index df0e2e3b5..d6ccdaaf9 100644 --- a/Adamant/Wallets/Dash/DashWalletService.swift +++ b/Adamant/Wallets/Dash/DashWalletService.swift @@ -96,10 +96,10 @@ class DashWalletService: WalletService { let transactionFeeUpdated = Notification.Name("adamant.dashWallet.feeUpdated") // MARK: - Delayed KVS save - private var balanceObserver: NSObjectProtocol? = nil + private var balanceObserver: NSObjectProtocol? // MARK: - Properties - private (set) var dashWallet: DashWallet? = nil + private (set) var dashWallet: DashWallet? private (set) var enabled = true @@ -144,7 +144,7 @@ class DashWalletService: WalletService { stateSemaphore.wait() switch state { - case .notInitiated, .updating, .initiationFailed(_): + case .notInitiated, .updating, .initiationFailed: return case .upToDate: diff --git a/Adamant/Wallets/Doge/DogeTransactionDetailsViewController.swift b/Adamant/Wallets/Doge/DogeTransactionDetailsViewController.swift index d5de5862a..be48cbd16 100644 --- a/Adamant/Wallets/Doge/DogeTransactionDetailsViewController.swift +++ b/Adamant/Wallets/Doge/DogeTransactionDetailsViewController.swift @@ -16,7 +16,7 @@ class DogeTransactionDetailsViewController: TransactionDetailsViewControllerBase // MARK: - Properties - private var cachedBlockInfo: (hash: String, height: String)? = nil + private var cachedBlockInfo: (hash: String, height: String)? private let autoupdateInterval: TimeInterval = 5.0 weak var timer: Timer? diff --git a/Adamant/Wallets/Doge/DogeTransactionsViewController.swift b/Adamant/Wallets/Doge/DogeTransactionsViewController.swift index 553b66144..fb5fd7127 100644 --- a/Adamant/Wallets/Doge/DogeTransactionsViewController.swift +++ b/Adamant/Wallets/Doge/DogeTransactionsViewController.swift @@ -75,7 +75,6 @@ class DogeTransactionsViewController: TransactionsListViewControllerBase { } } - // MARK: - UITableView override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -188,7 +187,7 @@ class DogeTransactionsViewController: TransactionsListViewControllerBase { private func loadMoreTransactions(from: Int) { let procedure = LoadMoreDogeTransactionsProcedure(service: walletService, from: from) - procedure.addDidFinishBlockObserver { [weak self] (procedure, error) in + procedure.addDidFinishBlockObserver { [weak self] (procedure, _) in guard let vc = self, let result = procedure.result else { return } @@ -216,12 +215,11 @@ class DogeTransactionsViewController: TransactionsListViewControllerBase { } } - private class LoadMoreDogeTransactionsProcedure: Procedure { let from: Int let service: DogeWalletService - private(set) var result: (transactions: [DogeTransaction], hasMore: Bool)? = nil + private(set) var result: (transactions: [DogeTransaction], hasMore: Bool)? init(service: DogeWalletService, from: Int) { self.from = from diff --git a/Adamant/Wallets/Doge/DogeTransferViewController.swift b/Adamant/Wallets/Doge/DogeTransferViewController.swift index ffa2a9656..d6037ce65 100644 --- a/Adamant/Wallets/Doge/DogeTransferViewController.swift +++ b/Adamant/Wallets/Doge/DogeTransferViewController.swift @@ -15,14 +15,12 @@ class DogeTransferViewController: TransferViewControllerBase { var chatsProvider: ChatsProvider! - // MARK: Properties private var skipValueChange: Bool = false static let invalidCharacters: CharacterSet = CharacterSet.decimalDigits.inverted - // MARK: Send override func sendFunds() { @@ -130,7 +128,6 @@ class DogeTransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -164,7 +161,7 @@ class DogeTransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = TextRow() { + let row = TextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.autocorrectionType = .no @@ -188,7 +185,7 @@ class DogeTransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/Doge/DogeWalletService+Send.swift b/Adamant/Wallets/Doge/DogeWalletService+Send.swift index cdad92f5a..f3e8da47b 100644 --- a/Adamant/Wallets/Doge/DogeWalletService+Send.swift +++ b/Adamant/Wallets/Doge/DogeWalletService+Send.swift @@ -29,7 +29,6 @@ extension DogeWalletService: WalletServiceTwoStepSend { return vc } - // MARK: Create & Send func createTransaction(recipient: String, amount: Decimal, completion: @escaping (WalletServiceResult) -> Void) { // MARK: 1. Prepare diff --git a/Adamant/Wallets/Doge/DogeWalletService.swift b/Adamant/Wallets/Doge/DogeWalletService.swift index 61eaf59dd..0c8809db2 100644 --- a/Adamant/Wallets/Doge/DogeWalletService.swift +++ b/Adamant/Wallets/Doge/DogeWalletService.swift @@ -92,10 +92,10 @@ class DogeWalletService: WalletService { let transactionFeeUpdated = Notification.Name("adamant.dogeWallet.feeUpdated") // MARK: - Delayed KVS save - private var balanceObserver: NSObjectProtocol? = nil + private var balanceObserver: NSObjectProtocol? // MARK: - Properties - private (set) var dogeWallet: DogeWallet? = nil + private (set) var dogeWallet: DogeWallet? private (set) var enabled = true @@ -158,7 +158,7 @@ class DogeWalletService: WalletService { stateSemaphore.wait() switch state { - case .notInitiated, .updating, .initiationFailed(_): + case .notInitiated, .updating, .initiationFailed: return case .upToDate: diff --git a/Adamant/Wallets/ERC20/ERC20TransactionsViewController.swift b/Adamant/Wallets/ERC20/ERC20TransactionsViewController.swift index 2cac852b0..159b6510e 100644 --- a/Adamant/Wallets/ERC20/ERC20TransactionsViewController.swift +++ b/Adamant/Wallets/ERC20/ERC20TransactionsViewController.swift @@ -41,7 +41,6 @@ class ERC20TransactionsViewController: TransactionsListViewControllerBase { handleRefresh(self.refreshControl) } - // MARK: - Overrides override func handleRefresh(_ refreshControl: UIRefreshControl) { @@ -153,7 +152,6 @@ class ERC20TransactionsViewController: TransactionsListViewControllerBase { } } - // MARK: - Tools extension ERC20TransactionsViewController { private func isOutgoing(_ transaction: EthTransactionShort) -> Bool { diff --git a/Adamant/Wallets/ERC20/ERC20TransferViewController.swift b/Adamant/Wallets/ERC20/ERC20TransferViewController.swift index 379d66e21..ad8dee477 100644 --- a/Adamant/Wallets/ERC20/ERC20TransferViewController.swift +++ b/Adamant/Wallets/ERC20/ERC20TransferViewController.swift @@ -15,7 +15,6 @@ class ERC20TransferViewController: TransferViewControllerBase { var chatsProvider: ChatsProvider! - // MARK: Properties private var skipValueChange: Bool = false @@ -107,7 +106,6 @@ class ERC20TransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -152,7 +150,7 @@ class ERC20TransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = TextRow() { + let row = TextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.keyboardType = UIKeyboardType.namePhonePad @@ -177,7 +175,7 @@ class ERC20TransferViewController: TransferViewControllerBase { $0.disabled = true // prefix.isEnabled = false } - }.cellUpdate { (cell, row) in + }.cellUpdate { (cell, _) in if let text = cell.textField.text { cell.textField.text = text.components(separatedBy: EthTransferViewController.invalidCharacters).joined() } @@ -205,7 +203,7 @@ class ERC20TransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/ERC20/ERC20WalletService+Send.swift b/Adamant/Wallets/ERC20/ERC20WalletService+Send.swift index 800a489b3..d0971aae5 100644 --- a/Adamant/Wallets/ERC20/ERC20WalletService+Send.swift +++ b/Adamant/Wallets/ERC20/ERC20WalletService+Send.swift @@ -23,7 +23,6 @@ extension ERC20WalletService: WalletServiceTwoStepSend { return vc } - // MARK: Create & Send func createTransaction(recipient: String, amount: Decimal, completion: @escaping (WalletServiceResult) -> Void) { // MARK: 1. Prepare diff --git a/Adamant/Wallets/ERC20/ERC20WalletService.swift b/Adamant/Wallets/ERC20/ERC20WalletService.swift index 593a21d78..247a1a7e4 100644 --- a/Adamant/Wallets/ERC20/ERC20WalletService.swift +++ b/Adamant/Wallets/ERC20/ERC20WalletService.swift @@ -118,12 +118,11 @@ class ERC20WalletService: WalletService { } } - private (set) var ethWallet: EthWallet? = nil + private (set) var ethWallet: EthWallet? var wallet: WalletAccount? { return ethWallet } - private (set) var contract: web3.web3contract? - private var balanceObserver: NSObjectProtocol? = nil + private var balanceObserver: NSObjectProtocol? init(token: ERC20Token) { self.token = token @@ -191,7 +190,7 @@ class ERC20WalletService: WalletService { stateSemaphore.wait() switch state { - case .notInitiated, .updating, .initiationFailed(_): + case .notInitiated, .updating, .initiationFailed: return case .upToDate: @@ -474,7 +473,6 @@ extension ERC20WalletService { } } - func getWalletAddress(byAdamantAddress address: String, completion: @escaping (WalletServiceResult) -> Void) { apiService.get(key: EthWalletService.kvsAddress, sender: address) { (result) in switch result { @@ -530,7 +528,7 @@ extension ERC20WalletService { // MARK: Sending requests let dispatchGroup = DispatchGroup() - var error: WalletServiceError? = nil + var error: WalletServiceError? var transactions = [EthTransactionShort]() let semaphore = DispatchSemaphore(value: 1) diff --git a/Adamant/Wallets/Ethereum/EthTransactionsViewController.swift b/Adamant/Wallets/Ethereum/EthTransactionsViewController.swift index 3f63599ed..fa575e49d 100644 --- a/Adamant/Wallets/Ethereum/EthTransactionsViewController.swift +++ b/Adamant/Wallets/Ethereum/EthTransactionsViewController.swift @@ -34,7 +34,6 @@ class EthTransactionsViewController: TransactionsListViewControllerBase { handleRefresh(self.refreshControl) } - // MARK: - Overrides override func handleRefresh(_ refreshControl: UIRefreshControl) { @@ -147,7 +146,6 @@ class EthTransactionsViewController: TransactionsListViewControllerBase { } } - // MARK: - Tools extension EthTransactionsViewController { private func isOutgoing(_ transaction: EthTransactionShort) -> Bool { diff --git a/Adamant/Wallets/Ethereum/EthTransferViewController.swift b/Adamant/Wallets/Ethereum/EthTransferViewController.swift index f141f2734..97e52a8df 100644 --- a/Adamant/Wallets/Ethereum/EthTransferViewController.swift +++ b/Adamant/Wallets/Ethereum/EthTransferViewController.swift @@ -15,7 +15,6 @@ class EthTransferViewController: TransferViewControllerBase { var chatsProvider: ChatsProvider! - // MARK: Properties private var skipValueChange: Bool = false @@ -24,7 +23,6 @@ class EthTransferViewController: TransferViewControllerBase { CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").inverted }() - // MARK: Send override func sendFunds() { @@ -102,7 +100,6 @@ class EthTransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -147,7 +144,7 @@ class EthTransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = TextRow() { + let row = TextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.keyboardType = UIKeyboardType.namePhonePad @@ -172,7 +169,7 @@ class EthTransferViewController: TransferViewControllerBase { $0.disabled = true // prefix.isEnabled = false } - }.cellUpdate { (cell, row) in + }.cellUpdate { (cell, _) in if let text = cell.textField.text { cell.textField.text = text.components(separatedBy: EthTransferViewController.invalidCharacters).joined() } @@ -200,7 +197,7 @@ class EthTransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/Ethereum/EthWalletService+Send.swift b/Adamant/Wallets/Ethereum/EthWalletService+Send.swift index 179463e66..f24a16e21 100644 --- a/Adamant/Wallets/Ethereum/EthWalletService+Send.swift +++ b/Adamant/Wallets/Ethereum/EthWalletService+Send.swift @@ -29,7 +29,6 @@ extension EthWalletService: WalletServiceTwoStepSend { return vc } - // MARK: Create & Send func createTransaction(recipient: String, amount: Decimal, completion: @escaping (WalletServiceResult) -> Void) { // MARK: 1. Prepare diff --git a/Adamant/Wallets/Ethereum/EthWalletService.swift b/Adamant/Wallets/Ethereum/EthWalletService.swift index 38137cbcc..05c2f32b9 100644 --- a/Adamant/Wallets/Ethereum/EthWalletService.swift +++ b/Adamant/Wallets/Ethereum/EthWalletService.swift @@ -89,14 +89,12 @@ class EthWalletService: WalletService { var dialogService: DialogService! var router: Router! - // MARK: - Notifications let walletUpdatedNotification = Notification.Name("adamant.ethWallet.walletUpdated") let serviceEnabledChanged = Notification.Name("adamant.ethWallet.enabledChanged") let transactionFeeUpdated = Notification.Name("adamant.ethWallet.feeUpdated") let serviceStateChanged = Notification.Name("adamant.ethWallet.stateChanged") - // MARK: RichMessageProvider properties static let richMessageType = "eth_transaction" let cellIdentifierSent = "ethTransferSent" @@ -152,13 +150,13 @@ class EthWalletService: WalletService { } } - private (set) var ethWallet: EthWallet? = nil + private (set) var ethWallet: EthWallet? private var waletStorage: EthWalletStorage? var wallet: WalletAccount? { return ethWallet } // MARK: - Delayed KVS save - private var balanceObserver: NSObjectProtocol? = nil + private var balanceObserver: NSObjectProtocol? // MARK: - Logic init() { @@ -221,7 +219,7 @@ class EthWalletService: WalletService { stateSemaphore.wait() switch state { - case .notInitiated, .updating, .initiationFailed(_): + case .notInitiated, .updating, .initiationFailed: return case .upToDate: @@ -325,7 +323,6 @@ class EthWalletService: WalletService { } } - // MARK: - WalletInitiatedWithPassphrase extension EthWalletService: InitiatedWithPassphraseService { func initWallet(withPassphrase passphrase: String, completion: @escaping (WalletServiceResult) -> Void) { @@ -424,7 +421,6 @@ extension EthWalletService: InitiatedWithPassphraseService { stateSemaphore.signal() } - /// New accounts doesn't have enought money to save KVS. We need to wait for balance update, and then - retry save private func kvsSaveCompletionRecursion(ethAddress: String, result: WalletServiceSimpleResult) { if let observer = balanceObserver { @@ -460,7 +456,6 @@ extension EthWalletService: InitiatedWithPassphraseService { } } - // MARK: - Dependencies extension EthWalletService: SwinjectDependentService { func injectDependencies(from container: Container) { @@ -471,7 +466,6 @@ extension EthWalletService: SwinjectDependentService { } } - // MARK: - Balances & addresses extension EthWalletService { func getBalance(forAddress address: EthereumAddress, completion: @escaping (WalletServiceResult) -> Void) { @@ -489,7 +483,6 @@ extension EthWalletService { } } - func getWalletAddress(byAdamantAddress address: String, completion: @escaping (WalletServiceResult) -> Void) { apiService.get(key: EthWalletService.kvsAddress, sender: address) { (result) in switch result { @@ -507,7 +500,6 @@ extension EthWalletService { } } - // MARK: - KVS extension EthWalletService { /// - Parameters: @@ -537,7 +529,6 @@ extension EthWalletService { } } - // MARK: - Transactions extension EthWalletService { func getTransaction(by hash: String, completion: @escaping (WalletServiceResult) -> Void) { @@ -660,7 +651,7 @@ extension EthWalletService { // MARK: Sending requests let dispatchGroup = DispatchGroup() - var error: WalletServiceError? = nil + var error: WalletServiceError? var transactions = [EthTransactionShort]() let semaphore = DispatchSemaphore(value: 1) @@ -727,7 +718,6 @@ extension EthWalletService { } } - /// Transaction history for Ropsten testnet func getTransactionsHistoryRopsten(address: String, page: Int = 1, size: Int = 50, completion: @escaping (WalletServiceResult<[EthTransaction]>) -> Void) { let queryItems: [URLQueryItem] = [URLQueryItem(name: "module", value: "account"), @@ -787,7 +777,6 @@ extension EthWalletService: PrivateKeyGenerator { return #imageLiteral(resourceName: "wallet_eth_row") } - func generatePrivateKeyFor(passphrase: String) -> String? { guard AdamantUtilities.validateAdamantPassphrase(passphrase: passphrase) else { return nil diff --git a/Adamant/Wallets/Lisk/LskTransactionDetailsViewController.swift b/Adamant/Wallets/Lisk/LskTransactionDetailsViewController.swift index f443ee109..e89233c2b 100644 --- a/Adamant/Wallets/Lisk/LskTransactionDetailsViewController.swift +++ b/Adamant/Wallets/Lisk/LskTransactionDetailsViewController.swift @@ -92,7 +92,7 @@ class LskTransactionDetailsViewController: TransactionDetailsViewControllerBase timer?.invalidate() } - func update(){ + func update() { guard let id = self.transaction?.txId, let service = self.service else { return } diff --git a/Adamant/Wallets/Lisk/LskTransactionsViewController.swift b/Adamant/Wallets/Lisk/LskTransactionsViewController.swift index 8c1077bdc..ba0fd780a 100644 --- a/Adamant/Wallets/Lisk/LskTransactionsViewController.swift +++ b/Adamant/Wallets/Lisk/LskTransactionsViewController.swift @@ -57,7 +57,6 @@ class LskTransactionsViewController: TransactionsListViewControllerBase { }) } - // MARK: - UITableView override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { diff --git a/Adamant/Wallets/Lisk/LskTransferViewController.swift b/Adamant/Wallets/Lisk/LskTransferViewController.swift index ab669d7fb..083e28214 100644 --- a/Adamant/Wallets/Lisk/LskTransferViewController.swift +++ b/Adamant/Wallets/Lisk/LskTransferViewController.swift @@ -15,12 +15,10 @@ class LskTransferViewController: TransferViewControllerBase { var chatsProvider: ChatsProvider! - // MARK: Properties private var skipValueChange: Bool = false - // MARK: Send override func sendFunds() { @@ -121,7 +119,6 @@ class LskTransferViewController: TransferViewControllerBase { } } - // MARK: Overrides private var _recipient: String? @@ -155,7 +152,7 @@ class LskTransferViewController: TransferViewControllerBase { } override func recipientRow() -> BaseRow { - let row = SuffixTextRow() { + let row = SuffixTextRow { $0.tag = BaseRows.address.tag $0.cell.textField.placeholder = String.adamantLocalized.newChat.addressPlaceholder $0.cell.textField.keyboardType = UIKeyboardType.alphabet @@ -169,7 +166,7 @@ class LskTransferViewController: TransferViewControllerBase { $0.disabled = true $0.cell.textField.isEnabled = false } - }.cellUpdate { (cell, row) in + }.cellUpdate { (cell, _) in if let text = cell.textField.text { cell.textField.text = text } @@ -189,7 +186,7 @@ class LskTransferViewController: TransferViewControllerBase { } self?.validateForm() - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let recipient = self?.recipientAddress { let text = recipient self?.shareValue(text, from: cell) diff --git a/Adamant/Wallets/Lisk/LskWalletService+Send.swift b/Adamant/Wallets/Lisk/LskWalletService+Send.swift index 91d254b11..4db331261 100644 --- a/Adamant/Wallets/Lisk/LskWalletService+Send.swift +++ b/Adamant/Wallets/Lisk/LskWalletService+Send.swift @@ -34,7 +34,6 @@ extension LskWalletService: WalletServiceTwoStepSend { return vc } - // MARK: Create & Send func createTransaction(recipient: String, amount: Decimal, completion: @escaping (WalletServiceResult) -> Void) { // MARK: 1. Prepare diff --git a/Adamant/Wallets/Lisk/LskWalletService.swift b/Adamant/Wallets/Lisk/LskWalletService.swift index f5982bc13..305752aeb 100644 --- a/Adamant/Wallets/Lisk/LskWalletService.swift +++ b/Adamant/Wallets/Lisk/LskWalletService.swift @@ -83,7 +83,7 @@ class LskWalletService: WalletService { internal var nodeApi: LiskKit.Node! internal var netHash: String = "" - private (set) var lskWallet: LskWallet? = nil + private (set) var lskWallet: LskWallet? let defaultDispatchQueue = DispatchQueue(label: "im.adamant.lskWalletService", qos: .utility, attributes: [.concurrent]) @@ -110,8 +110,7 @@ class LskWalletService: WalletService { let stateSemaphore = DispatchSemaphore(value: 1) // MARK: - Delayed KVS save - private var balanceObserver: NSObjectProtocol? = nil - + private var balanceObserver: NSObjectProtocol? // MARK: - Logic convenience init(mainnet: Bool = true) { @@ -161,7 +160,7 @@ class LskWalletService: WalletService { stateSemaphore.wait() switch state { - case .notInitiated, .updating, .initiationFailed(_): + case .notInitiated, .updating, .initiationFailed: return case .upToDate: @@ -302,7 +301,7 @@ extension LskWalletService { let group = DispatchGroup() group.enter() - initiateNodes { result in + initiateNodes { _ in group.leave() } @@ -415,7 +414,6 @@ extension LskWalletService: InitiatedWithPassphraseService { stateSemaphore.signal() } - /// New accounts doesn't have enought money to save KVS. We need to wait for balance update, and then - retry save private func kvsSaveCompletionRecursion(lskAddress: String, result: WalletServiceSimpleResult) { if let observer = balanceObserver { @@ -516,7 +514,6 @@ extension LskWalletService { } } - // MARK: - KVS extension LskWalletService { /// - Parameters: @@ -602,7 +599,6 @@ extension LskWalletService: PrivateKeyGenerator { return #imageLiteral(resourceName: "wallet_lsk_row") } - func generatePrivateKeyFor(passphrase: String) -> String? { guard AdamantUtilities.validateAdamantPassphrase(passphrase: passphrase), let keypair = try? LiskKit.Crypto.keyPair(fromPassphrase: passphrase, salt: "adm") else { return nil diff --git a/Adamant/Wallets/TransactionDetailsViewControllerBase.swift b/Adamant/Wallets/TransactionDetailsViewControllerBase.swift index ffb204f20..c519cb3c3 100644 --- a/Adamant/Wallets/TransactionDetailsViewControllerBase.swift +++ b/Adamant/Wallets/TransactionDetailsViewControllerBase.swift @@ -118,7 +118,7 @@ class TransactionDetailsViewControllerBase: FormViewController { // MARK: - Properties - var transaction: TransactionDetails? = nil { + var transaction: TransactionDetails? { didSet { if !isFiatSet { self.updateFiat() @@ -167,7 +167,7 @@ class TransactionDetailsViewControllerBase: FormViewController { } // MARK: Transaction number - let idRow = LabelRow() { + let idRow = LabelRow { $0.disabled = true $0.tag = Rows.transactionNumber.tag $0.title = Rows.transactionNumber.localized @@ -196,7 +196,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(idRow) // MARK: Sender - let senderRow = DoubleDetailsRow() { [weak self] in + let senderRow = DoubleDetailsRow { [weak self] in $0.disabled = true $0.tag = Rows.from.tag $0.cell.titleLabel.text = Rows.from.localized @@ -249,7 +249,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(senderRow) // MARK: Recipient - let recipientRow = DoubleDetailsRow() { [weak self] in + let recipientRow = DoubleDetailsRow { [weak self] in $0.disabled = true $0.tag = Rows.to.tag $0.cell.titleLabel.text = Rows.to.localized @@ -288,7 +288,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(recipientRow) // MARK: Date - let dateRow = LabelRow() { [weak self] in + let dateRow = LabelRow { [weak self] in $0.disabled = true $0.tag = Rows.date.tag $0.title = Rows.date.localized @@ -300,7 +300,7 @@ class TransactionDetailsViewControllerBase: FormViewController { } }.cellSetup { (cell, _) in cell.selectionStyle = .gray - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (cell, _) in if let value = self?.transaction?.dateValue { let text = value.humanizedDateTimeFull() self?.shareValue(text, from: cell) @@ -318,7 +318,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(dateRow) // MARK: Amount - let amountRow = LabelRow() { + let amountRow = LabelRow { $0.disabled = true $0.tag = Rows.amount.tag $0.title = Rows.amount.localized @@ -346,7 +346,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(amountRow) // MARK: Fee - let feeRow = LabelRow() { + let feeRow = LabelRow { $0.disabled = true $0.tag = Rows.fee.tag $0.title = Rows.fee.localized @@ -375,7 +375,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(feeRow) // MARK: Confirmations - let confirmationsRow = LabelRow() { + let confirmationsRow = LabelRow { $0.disabled = true $0.tag = Rows.confirmations.tag $0.title = Rows.confirmations.localized @@ -386,7 +386,6 @@ class TransactionDetailsViewControllerBase: FormViewController { $0.value = TransactionDetailsViewControllerBase.awaitingValueString } - }.cellSetup { (cell, _) in cell.selectionStyle = .gray }.onCellSelection { [weak self] (cell, row) in @@ -406,7 +405,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(confirmationsRow) // MARK: Block - let blockRow = LabelRow() { + let blockRow = LabelRow { $0.disabled = true $0.tag = Rows.block.tag $0.title = Rows.block.localized @@ -437,7 +436,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(blockRow) // MARK: Status - let statusRow = LabelRow() { + let statusRow = LabelRow { $0.tag = Rows.status.tag $0.title = Rows.status.localized $0.value = transaction?.transactionStatus?.localized @@ -459,7 +458,7 @@ class TransactionDetailsViewControllerBase: FormViewController { detailsSection.append(statusRow) // MARK: Current Fiat - let currentFiatRow = LabelRow() { + let currentFiatRow = LabelRow { $0.disabled = true $0.tag = Rows.currentFiat.tag $0.title = Rows.currentFiat.localized @@ -494,7 +493,7 @@ class TransactionDetailsViewControllerBase: FormViewController { form.append(detailsSection) // MARK: History Fiat - let fiatRow = LabelRow() { + let fiatRow = LabelRow { $0.disabled = true $0.tag = Rows.historyFiat.tag $0.title = Rows.historyFiat.localized @@ -665,12 +664,12 @@ class TransactionDetailsViewControllerBase: FormViewController { // MARK: - To override - var currencySymbol: String? = nil + var currencySymbol: String? // MARK: - Fix this later - var senderName: String? = nil - var recipientName: String? = nil - var comment: String? = nil + var senderName: String? + var recipientName: String? + var comment: String? func explorerUrl(for transaction: TransactionDetails) -> URL? { return nil diff --git a/Adamant/Wallets/TransactionTableViewCell.swift b/Adamant/Wallets/TransactionTableViewCell.swift index 8977f977c..ee06993f7 100644 --- a/Adamant/Wallets/TransactionTableViewCell.swift +++ b/Adamant/Wallets/TransactionTableViewCell.swift @@ -34,13 +34,11 @@ class TransactionTableViewCell: UITableViewCell { } } - // MARK: - Constants static let cellHeightCompact: CGFloat = 90.0 static let cellHeightFull: CGFloat = 100.0 - // MARK: - IBOutlets @IBOutlet weak var topImageView: UIImageView! @@ -50,7 +48,6 @@ class TransactionTableViewCell: UITableViewCell { @IBOutlet weak var ammountLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! - // MARK: - Properties var transactionType: TransactionType = .income { @@ -61,7 +58,6 @@ class TransactionTableViewCell: UITableViewCell { } } - // MARK: - Initializers override func awakeFromNib() { diff --git a/Adamant/Wallets/TransactionsListViewControllerBase.swift b/Adamant/Wallets/TransactionsListViewControllerBase.swift index adbb79dad..db5ed43ea 100644 --- a/Adamant/Wallets/TransactionsListViewControllerBase.swift +++ b/Adamant/Wallets/TransactionsListViewControllerBase.swift @@ -33,12 +33,10 @@ class TransactionsListViewControllerBase: UIViewController { return refreshControl }() - // MARK: - IBOutlets @IBOutlet weak var tableView: UITableView! @IBOutlet weak var emptyLabel: UILabel! - // MARK: - Lifecycle override func viewDidLoad() { @@ -60,7 +58,7 @@ class TransactionsListViewControllerBase: UIViewController { tableView.refreshControl = refreshControl // MARK: Notifications - NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: OperationQueue.main) { [weak self] notification in + NotificationCenter.default.addObserver(forName: Notification.Name.AdamantAccountService.userLoggedIn, object: nil, queue: OperationQueue.main) { [weak self] _ in self?.reloadData() } @@ -86,7 +84,6 @@ class TransactionsListViewControllerBase: UIViewController { } } - // MARK: - To override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { @@ -113,7 +110,7 @@ class TransactionsListViewControllerBase: UIViewController { } - var currencySymbol: String? = nil + var currencySymbol: String? } // MARK: - UITableViewDataSource, UITableViewDelegate diff --git a/Adamant/Wallets/TransferViewControllerBase+Alert.swift b/Adamant/Wallets/TransferViewControllerBase+Alert.swift index 64691c10c..c09f122cb 100644 --- a/Adamant/Wallets/TransferViewControllerBase+Alert.swift +++ b/Adamant/Wallets/TransferViewControllerBase+Alert.swift @@ -49,7 +49,6 @@ extension TransferViewControllerBase { hideView(progressView, animated: animated) } - // MARK: - Alert view func showAlertView(title: String?, message: String, animated: Bool) { @@ -94,7 +93,6 @@ extension TransferViewControllerBase { hideView(alertView, animated: animated) } - // MARK: - Tools private func hideView(_ view: UIView, animated: Bool) { let callback: () -> Void @@ -103,7 +101,7 @@ extension TransferViewControllerBase { callback = { UIView.animate(withDuration: 0.2, animations: { view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0) - }, completion: { success in + }, completion: { _ in view.removeFromSuperview() }) } diff --git a/Adamant/Wallets/TransferViewControllerBase+QR.swift b/Adamant/Wallets/TransferViewControllerBase+QR.swift index 9e5356544..5dab09893 100644 --- a/Adamant/Wallets/TransferViewControllerBase+QR.swift +++ b/Adamant/Wallets/TransferViewControllerBase+QR.swift @@ -12,7 +12,6 @@ import EFQRCode import AVFoundation import Photos - // MARK: - QR extension TransferViewControllerBase { func scanQr() { diff --git a/Adamant/Wallets/TransferViewControllerBase.swift b/Adamant/Wallets/TransferViewControllerBase.swift index c3ea12a92..80feed155 100644 --- a/Adamant/Wallets/TransferViewControllerBase.swift +++ b/Adamant/Wallets/TransferViewControllerBase.swift @@ -10,14 +10,12 @@ import UIKit import Eureka import QRCodeReader - // MARK: - Transfer Delegate Protocol protocol TransferViewControllerDelegate: AnyObject { func transferViewController(_ viewController: TransferViewControllerBase, didFinishWithTransfer transfer: TransactionDetails?, detailsViewController: UIViewController?) } - // MARK: - Localization extension String.adamantLocalized { struct transfer { @@ -50,8 +48,6 @@ fileprivate extension String.adamantLocalized.alert { static let send = NSLocalizedString("TransferScene.Send", comment: "Transfer: Confirm transfer alert: Send tokens button") } - - // MARK: - class TransferViewControllerBase: FormViewController { @@ -125,7 +121,6 @@ class TransferViewControllerBase: FormViewController { } } - // MARK: - Dependencies var accountService: AccountService! @@ -134,7 +129,6 @@ class TransferViewControllerBase: FormViewController { var router: Router! var currencyInfoService: CurrencyInfoService! - // MARK: - Properties var commentsEnabled: Bool = false @@ -171,10 +165,9 @@ class TransferViewControllerBase: FormViewController { } } - weak var delegate: TransferViewControllerDelegate? - var recipientAddress: String? = nil { + var recipientAddress: String? { didSet { if let row: RowOf = form.rowBy(tag: BaseRows.address.tag) { row.value = recipientAddress @@ -185,7 +178,7 @@ class TransferViewControllerBase: FormViewController { private var recipientAddressIsValid = false - var recipientName: String? = nil { + var recipientName: String? { didSet { guard let row: RowOf = form.rowBy(tag: BaseRows.name.tag) else { return @@ -197,12 +190,12 @@ class TransferViewControllerBase: FormViewController { } } - var admReportRecipient: String? = nil - var amount: Decimal? = nil + var admReportRecipient: String? + var amount: Decimal? var recipientIsReadonly = false - var rate: Decimal? = nil + var rate: Decimal? var maxToTransfer: Decimal { guard @@ -224,7 +217,6 @@ class TransferViewControllerBase: FormViewController { return accessory } - // MARK: - QR Reader lazy var qrReader: QRCodeReaderViewController = { @@ -239,11 +231,9 @@ class TransferViewControllerBase: FormViewController { return vc }() - // MARK: - Alert - var progressView: UIView? = nil - var alertView: UIView? = nil - + var progressView: UIView? + var alertView: UIView? // MARK: - Lifecycle @@ -267,11 +257,11 @@ class TransferViewControllerBase: FormViewController { // MARK: Button section form +++ Section() - <<< ButtonRow() { [weak self] in + <<< ButtonRow { [weak self] in $0.title = BaseRows.sendButton.localized $0.tag = BaseRows.sendButton.tag - $0.disabled = Condition.function([BaseRows.address.tag, BaseRows.amount.tag]) { [weak self] form -> Bool in + $0.disabled = Condition.function([BaseRows.address.tag, BaseRows.amount.tag]) { [weak self] _ -> Bool in guard let service = self?.service, let wallet = service.wallet, wallet.balance > service.transactionFee else { return true } @@ -282,7 +272,7 @@ class TransferViewControllerBase: FormViewController { return !isValid } - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in self?.confirmSendFunds() } @@ -366,7 +356,6 @@ class TransferViewControllerBase: FormViewController { return section } - // MARK: - Tools @@ -538,8 +527,6 @@ class TransferViewControllerBase: FormViewController { } } - - // MARK: - 'Virtual' methods with basic implementation /// Currency code, used to get fiat rates @@ -603,8 +590,7 @@ class TransferViewControllerBase: FormViewController { return WalletViewControllerBase.BaseRows.send.localized } - - /// MARK: - Abstract + // MARK: - Abstract /// Send funds to recipient after validations /// You must override this method @@ -622,14 +608,12 @@ class TransferViewControllerBase: FormViewController { fatalError("You must implement raw address handling") } - /// Build recipient address row /// You must override this method func recipientRow() -> BaseRow { fatalError("You must implement recipient row") } - /// Validate recipient's address /// You must override this method func validateRecipient(_ address: String) -> Bool { @@ -637,13 +621,12 @@ class TransferViewControllerBase: FormViewController { } } - // MARK: - Default rows extension TransferViewControllerBase { func defaultRowFor(baseRow: BaseRows) -> BaseRow { switch baseRow { case .balance: - return DecimalRow() { [weak self] in + return DecimalRow { [weak self] in $0.title = BaseRows.balance.localized $0.tag = BaseRows.balance.tag $0.disabled = true @@ -657,7 +640,7 @@ extension TransferViewControllerBase { } case .name: - let row = LabelRow() { [weak self] in + let row = LabelRow { [weak self] in $0.title = BaseRows.name.localized $0.tag = BaseRows.name.tag $0.value = self?.recipientName @@ -676,7 +659,7 @@ extension TransferViewControllerBase { return recipientRow() case .maxToTransfer: - let row = DecimalRow() { [weak self] in + let row = DecimalRow { [weak self] in $0.title = BaseRows.maxToTransfer.localized $0.tag = BaseRows.maxToTransfer.tag $0.disabled = true @@ -686,7 +669,7 @@ extension TransferViewControllerBase { if let maxToTransfer = self?.maxToTransfer { $0.value = maxToTransfer.doubleValue } - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, row) in guard let value = row.value, value > 0, let presenter = self else { row.deselect(animated: true) return @@ -757,7 +740,7 @@ extension TransferViewControllerBase { } case .fee: - return DecimalRow() { [weak self] in + return DecimalRow { [weak self] in $0.tag = BaseRows.fee.tag $0.title = BaseRows.fee.localized $0.disabled = true @@ -771,7 +754,7 @@ extension TransferViewControllerBase { } case .total: - return DecimalRow() { [weak self] in + return DecimalRow { [weak self] in $0.tag = BaseRows.total.tag $0.title = BaseRows.total.localized $0.value = nil @@ -784,7 +767,7 @@ extension TransferViewControllerBase { } case .comments: - let row = TextAreaRow() { + let row = TextAreaRow { $0.tag = BaseRows.comments.tag $0.textAreaHeight = .dynamic(initialTextViewHeight: 44) }.cellUpdate { (cell, _) in @@ -794,11 +777,11 @@ extension TransferViewControllerBase { return row case .sendButton: - return ButtonRow() { [weak self] in + return ButtonRow { [weak self] in $0.title = BaseRows.sendButton.localized $0.tag = BaseRows.sendButton.tag - $0.disabled = Condition.function([BaseRows.address.tag, BaseRows.amount.tag]) { [weak self] form -> Bool in + $0.disabled = Condition.function([BaseRows.address.tag, BaseRows.amount.tag]) { [weak self] _ -> Bool in guard let service = self?.service, let wallet = service.wallet, wallet.balance > service.transactionFee else { return true } @@ -809,7 +792,7 @@ extension TransferViewControllerBase { return !isValid } - }.onCellSelection { [weak self] (cell, row) in + }.onCellSelection { [weak self] (_, _) in self?.confirmSendFunds() } } diff --git a/Adamant/Wallets/WalletService.swift b/Adamant/Wallets/WalletService.swift index 93225efbb..890528cec 100644 --- a/Adamant/Wallets/WalletService.swift +++ b/Adamant/Wallets/WalletService.swift @@ -125,7 +125,7 @@ extension ChatsProviderError { case .notLogged: return .notLogged - case .messageNotValid(_): + case .messageNotValid: return .notLogged case .notEnoughMoneyToSend: @@ -140,7 +140,7 @@ extension ChatsProviderError { case .serverError(let e): return .internalError(message: self.message, error: e) - case .accountNotFound(_): + case .accountNotFound: return .accountNotFound case .dependencyError(let message): @@ -152,13 +152,12 @@ extension ChatsProviderError { case .internalError(let error): return .internalError(message: self.message, error: error) - case .accountNotInitiated(_): + case .accountNotInitiated: return .walletNotInitiated } } } - // MARK: - Notifications extension AdamantUserInfoKey { struct WalletService { @@ -169,7 +168,6 @@ extension AdamantUserInfoKey { } } - // MARK: - UI extension Notification.Name { struct WalletViewController { @@ -185,7 +183,6 @@ protocol WalletViewController { var service: WalletService? { get } } - // MARK: - Wallet Service protocol WalletService: AnyObject { // MARK: Currency diff --git a/Adamant/Wallets/WalletViewControllerBase.swift b/Adamant/Wallets/WalletViewControllerBase.swift index 9cf1b6b1a..4031d272d 100644 --- a/Adamant/Wallets/WalletViewControllerBase.swift +++ b/Adamant/Wallets/WalletViewControllerBase.swift @@ -44,13 +44,11 @@ class WalletViewControllerBase: FormViewController, WalletViewController { private let cellIdentifier = "cell" - // MARK: - Dependencies var dialogService: DialogService! var currencyInfoService: CurrencyInfoService! - // MARK: - Properties, WalletViewController var viewController: UIViewController { return self } @@ -89,7 +87,7 @@ class WalletViewControllerBase: FormViewController, WalletViewController { section.append(addressRow) // MARK: Balance - let balanceRow = BalanceRow() { [weak self] in + let balanceRow = BalanceRow { [weak self] in $0.tag = BaseRows.balance.tag $0.cell.titleLabel.text = BaseRows.balance.localized @@ -123,7 +121,7 @@ class WalletViewControllerBase: FormViewController, WalletViewController { balanceRow.cell.selectionStyle = .gray balanceRow.cellUpdate { (cell, _) in cell.accessoryType = .disclosureIndicator - }.onCellSelection { [weak self] (_, row) in + }.onCellSelection { [weak self] (_, _) in guard let service = self?.service as? WalletServiceWithTransfers else { return } @@ -148,13 +146,13 @@ class WalletViewControllerBase: FormViewController, WalletViewController { if service is WalletServiceWithSend { let label = sendRowLocalizedLabel() - let sendRow = LabelRow() { + let sendRow = LabelRow { $0.tag = BaseRows.send.tag $0.title = label $0.cell.selectionStyle = .gray }.cellUpdate { (cell, _) in cell.accessoryType = .disclosureIndicator - }.onCellSelection { [weak self] (_, row) in + }.onCellSelection { [weak self] (_, _) in guard let service = self?.service as? WalletServiceWithSend else { return } @@ -189,7 +187,7 @@ class WalletViewControllerBase: FormViewController, WalletViewController { // MARK: Notification if let service = service { // MARK: Wallet updated - let walletUpdatedCallback = { [weak self] (notification: Notification) in + let walletUpdatedCallback = { [weak self] (_: Notification) in if let row: LabelRow = self?.form.rowBy(tag: BaseRows.address.tag) { if let wallet = service.wallet { row.value = wallet.address @@ -267,7 +265,6 @@ class WalletViewControllerBase: FormViewController, WalletViewController { return UIView() } - // MARK: - To override func sendRowLocalizedLabel() -> String { @@ -283,7 +280,7 @@ class WalletViewControllerBase: FormViewController, WalletViewController { } func adressRow() -> LabelRow { - let addressRow = LabelRow() { + let addressRow = LabelRow { $0.tag = BaseRows.address.tag $0.title = BaseRows.address.localized $0.cell.selectionStyle = .gray @@ -389,7 +386,6 @@ class WalletViewControllerBase: FormViewController, WalletViewController { } } - // MARK: - TransferViewControllerDelegate extension WalletViewControllerBase: TransferViewControllerDelegate { func transferViewController(_ viewController: TransferViewControllerBase, didFinishWithTransfer transfer: TransactionDetails?, detailsViewController: UIViewController?) { diff --git a/AdamantShared/AdamantResources.swift b/AdamantShared/AdamantResources.swift index 3cde355d5..547659817 100644 --- a/AdamantShared/AdamantResources.swift +++ b/AdamantShared/AdamantResources.swift @@ -20,7 +20,7 @@ struct AdamantResources { Node(scheme: .https, host: "debate.adamant.im", port: nil), Node(scheme: .https, host: "bid.adamant.im", port: nil), Node(scheme: .https, host: "unusual.adamant.im", port: nil), - Node(scheme: .http, host: "23.226.231.225", port: 36666), + Node(scheme: .http, host: "23.226.231.225", port: 36666) // Node(scheme: .http, host: "80.211.177.181", port: 36666), // Node(scheme: .http, host: "80.211.177.181", port: nil), // Bugged one // Node(scheme: .http, host: "163.172.132.38", port: 36667) // Testnet diff --git a/AdamantShared/Core/Crypto.swift b/AdamantShared/Core/Crypto.swift index 3f8bf223d..6d1001e69 100644 --- a/AdamantShared/Core/Crypto.swift +++ b/AdamantShared/Core/Crypto.swift @@ -10,7 +10,7 @@ import Foundation import Clibsodium import CryptoSwift -public typealias Bytes = Array +public typealias Bytes = [UInt8] struct Crypto { static let sign = Sign() @@ -39,9 +39,9 @@ struct Sign { func signature(message: Bytes, secretKey: Bytes) -> Bytes? { guard secretKey.count == SecretKeyBytes else { return nil } - var signature = Array(count: SignBytes) + var signature = [UInt8](count: SignBytes) - guard .SUCCESS == crypto_sign_detached ( + guard .SUCCESS == crypto_sign_detached( &signature, nil, message, UInt64(message.count), @@ -135,7 +135,7 @@ struct SecretBox: NonceGenerator { var authenticatedCipherText = Bytes(count: message.count + MacBytes) let nonce = self.nonce() - guard .SUCCESS == crypto_secretbox_easy ( + guard .SUCCESS == crypto_secretbox_easy( &authenticatedCipherText, message, UInt64(message.count), nonce, @@ -149,7 +149,7 @@ struct SecretBox: NonceGenerator { guard authenticatedCipherText.count >= MacBytes else { return nil } var message = Bytes(count: authenticatedCipherText.count - MacBytes) - guard .SUCCESS == crypto_secretbox_open_easy ( + guard .SUCCESS == crypto_secretbox_open_easy( &message, authenticatedCipherText, UInt64(authenticatedCipherText.count), nonce, @@ -191,7 +191,7 @@ extension ArraySlice where Element == UInt8 { var bytes: Bytes { return Bytes(self) } } -fileprivate enum ExitCode { +private enum ExitCode { case SUCCESS case FAILURE diff --git a/AdamantShared/Core/NativeAdamantCore.swift b/AdamantShared/Core/NativeAdamantCore.swift index db7a5ca39..44cc9d06e 100644 --- a/AdamantShared/Core/NativeAdamantCore.swift +++ b/AdamantShared/Core/NativeAdamantCore.swift @@ -67,7 +67,6 @@ class NativeAdamantCore { return decrepted.utf8String } - // MARK: - Values func encodeValue(_ value: [String: Any], privateKey privateKeyHex: String) -> (message: String, nonce: String)? { diff --git a/AdamantShared/ExtensionsTools/ExtensionsApi.swift b/AdamantShared/ExtensionsTools/ExtensionsApi.swift index d22642d6e..a563b420c 100644 --- a/AdamantShared/ExtensionsTools/ExtensionsApi.swift +++ b/AdamantShared/ExtensionsTools/ExtensionsApi.swift @@ -26,7 +26,7 @@ class ExtensionsApi { } }() - private var currentNode: Node? = nil + private var currentNode: Node? private func selectNewNode() { currentNode = nodes.popLast() @@ -42,7 +42,7 @@ class ExtensionsApi { // MARK: Transactions func getTransaction(by id: UInt64) -> Transaction? { // MARK: 1. Getting Transaction - var response: ServerModelResponse? = nil + var response: ServerModelResponse? var nodeUrl: URL! = nil if currentNode == nil { selectNewNode() @@ -115,7 +115,7 @@ class ExtensionsApi { // MARK: Address book func getAddressBook(for address: String, core: NativeAdamantCore, keypair: Keypair) -> [String:ContactDescription]? { - var response: ServerCollectionResponse? = nil + var response: ServerCollectionResponse? // Getting transaction repeat { diff --git a/AdamantShared/Helpers/AdamantBalanceFormat.swift b/AdamantShared/Helpers/AdamantBalanceFormat.swift index 1a6f73a1d..f2e8a4f3e 100644 --- a/AdamantShared/Helpers/AdamantBalanceFormat.swift +++ b/AdamantShared/Helpers/AdamantBalanceFormat.swift @@ -24,7 +24,6 @@ enum AdamantBalanceFormat { /// 2 digits after the decimal point case short - // MARK: Formatters static func currencyFormatter(for format: AdamantBalanceFormat, currencySymbol symbol: String?) -> NumberFormatter { @@ -129,7 +128,6 @@ enum AdamantBalanceFormat { } } - // MARK: - Helper extension NumberFormatter { func string(from decimal: Decimal) -> String? { diff --git a/AdamantShared/Helpers/AdamantUtilities.swift b/AdamantShared/Helpers/AdamantUtilities.swift index d81fbe901..4f17d1459 100644 --- a/AdamantShared/Helpers/AdamantUtilities.swift +++ b/AdamantShared/Helpers/AdamantUtilities.swift @@ -30,7 +30,6 @@ class AdamantUtilities { return components.date!.timeIntervalSince1970 }() - // MARK: - JSON static func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { diff --git a/AdamantShared/Helpers/Date+adamant.swift b/AdamantShared/Helpers/Date+adamant.swift index 988e42398..4016f3f96 100644 --- a/AdamantShared/Helpers/Date+adamant.swift +++ b/AdamantShared/Helpers/Date+adamant.swift @@ -44,7 +44,6 @@ extension Date { return DateFormatter.localizedString(from: self, dateStyle: .long, timeStyle: .short) } - /// Returns readable day string. "Today, Yesterday, etc" func humanizedDay() -> String { let dateString: String @@ -64,14 +63,12 @@ extension Date { return dateString } - /// Returns readable time string. "Just now, minutes ago, 11:30, etc" /// - Returns: Readable string, and time when string will be expired and needs an update func humanizedTime() -> (string: String, expireIn: TimeInterval?) { let timeString: String let expire: TimeInterval? - let seconds = secondsAgo if seconds < 30 { timeString = NSLocalizedString("Just now", tableName: "DateTools", bundle: Bundle.dateToolsBundle(), comment: "") @@ -91,7 +88,6 @@ extension Date { return (timeString, expire) } - // MARK: Formatters private static let formatterWeekDayMonth: DateFormatter = { diff --git a/AdamantShared/Helpers/UIColor+adamant.swift b/AdamantShared/Helpers/UIColor+adamant.swift index 4909fdcc2..b5ed27d5f 100644 --- a/AdamantShared/Helpers/UIColor+adamant.swift +++ b/AdamantShared/Helpers/UIColor+adamant.swift @@ -46,12 +46,10 @@ extension UIColor { /// Partner chat bubble background, ~8% gray static let chatSenderBackground = UIColor(red: 0.925, green: 0.925, blue: 0.925, alpha: 1) - // MARK: Pinpad /// Pinpad highligh button background, 12% gray static let pinpadHighlightButton = UIColor(red: 0.88, green: 0.88, blue: 0.88, alpha: 1) - // MARK: Transfers /// Income transfer icon background, light green static let transferIncomeIconBackground = UIColor(red: 0.7, green: 0.93, blue: 0.55, alpha: 1) diff --git a/AdamantShared/Localization/AdamantLocalized.swift b/AdamantShared/Localization/AdamantLocalized.swift index ec6751bc5..c2d9e90b4 100644 --- a/AdamantShared/Localization/AdamantLocalized.swift +++ b/AdamantShared/Localization/AdamantLocalized.swift @@ -35,4 +35,3 @@ public extension String { } } } - diff --git a/AdamantShared/Models/RichMessage.swift b/AdamantShared/Models/RichMessage.swift index 8322234d3..296a61c2c 100644 --- a/AdamantShared/Models/RichMessage.swift +++ b/AdamantShared/Models/RichMessage.swift @@ -33,7 +33,6 @@ struct RichContentKeys { private init() {} } - // MARK: - RichMessageTransfer struct RichMessageTransfer: RichMessage { diff --git a/AdamantShared/Models/ServerResponse.swift b/AdamantShared/Models/ServerResponse.swift index 8b7aec2ed..3cf4f85a8 100644 --- a/AdamantShared/Models/ServerResponse.swift +++ b/AdamantShared/Models/ServerResponse.swift @@ -48,7 +48,7 @@ class ServerResponse: Decodable { } } -class ServerModelResponse: ServerResponse { +class ServerModelResponse: ServerResponse { let model: T? required init(from decoder: Decoder) throws { @@ -62,7 +62,7 @@ class ServerModelResponse: ServerResponse { } } -class ServerCollectionResponse: ServerResponse { +class ServerCollectionResponse: ServerResponse { let collection: [T]? required init(from decoder: Decoder) throws { @@ -76,7 +76,6 @@ class ServerCollectionResponse: ServerResponse { } } - // MARK: - JSON /* { diff --git a/AdamantShared/Models/Transaction.swift b/AdamantShared/Models/Transaction.swift index 0cc7fc11c..4fc9e5de6 100644 --- a/AdamantShared/Models/Transaction.swift +++ b/AdamantShared/Models/Transaction.swift @@ -118,7 +118,6 @@ extension Transaction: WrappableCollection { static let CollectionKey = "transactions" } - // MARK: - JSON /* Fund transfers { diff --git a/AdamantShared/RichMessageProviders/TransferBaseProvider.swift b/AdamantShared/RichMessageProviders/TransferBaseProvider.swift index b3a6a75b7..331ab67b6 100644 --- a/AdamantShared/RichMessageProviders/TransferBaseProvider.swift +++ b/AdamantShared/RichMessageProviders/TransferBaseProvider.swift @@ -28,7 +28,6 @@ class TransferBaseProvider: TransferNotificationContentProvider { return notificationContent(partnerAddress: partnerAddress, partnerName: partnerName, amount: amount, comment: comment) } - /// Create notification content for rich transfers with comments, such as ADM transfer func notificationContent(partnerAddress: String, partnerName: String?, amount: Decimal, comment: String?) -> NotificationContent? { let amountFormated = AdamantBalanceFormat.full.format(amount, withCurrencySymbol: currencySymbol) @@ -92,4 +91,3 @@ class TransferBaseProvider: TransferNotificationContentProvider { return url } } - diff --git a/AdamantShared/Services/AdamantAvatarService.swift b/AdamantShared/Services/AdamantAvatarService.swift index e83ea06fb..5355e0a74 100644 --- a/AdamantShared/Services/AdamantAvatarService.swift +++ b/AdamantShared/Services/AdamantAvatarService.swift @@ -81,8 +81,8 @@ class AdamantAvatarService { let fillTriangle = triangleColors(0, key, Int(lines)) let transparent = UIColor.clear - let isLeft: (Int)->Bool = { (v: Int) -> Bool in return (v % 2) == 0 } - let isRight: (Int)->Bool = { (v: Int) -> Bool in return (v % 2) != 0 } + let isLeft: (Int) -> Bool = { (v: Int) -> Bool in return (v % 2) == 0 } + let isRight: (Int) -> Bool = { (v: Int) -> Bool in return (v % 2) != 0 } let L = Int(lines) let hL = L / 2 @@ -372,7 +372,7 @@ class AdamantAvatarService { // canFill returns a fill svg string given position. the fill is computed to be a rotation of the // triangle 0 with the 'fills' array given as param. - func canFill(_ x: Int, _ y: Int, _ fills: [UIColor], _ isLeft: (Int)->Bool, _ isRight: (Int)->Bool) -> UIColor? { + func canFill(_ x: Int, _ y: Int, _ fills: [UIColor], _ isLeft: (Int) -> Bool, _ isRight: (Int) -> Bool) -> UIColor? { let l = Triangle(x, y, .left) let r = Triangle(x, y, .right) @@ -387,7 +387,7 @@ class AdamantAvatarService { } } -fileprivate struct Triangle { +private struct Triangle { let x: Int let y: Int let direction: Direction @@ -514,7 +514,7 @@ fileprivate struct Triangle { 5: [5, 7, 6, 3, 1, 2], 6: [6, 3, 1, 2, 5, 7], 7: [7, 5, 4, 1, 3, 4], - 8: [8, 8, 2, 0, 0, 6], + 8: [8, 8, 2, 0, 0, 6] ] return m[lookforSubTriangleID] } @@ -536,7 +536,7 @@ fileprivate struct Triangle { } } -fileprivate enum Direction: Int { +private enum Direction: Int { case left = 0 case right } diff --git a/AdamantShared/Services/KeychainStore.swift b/AdamantShared/Services/KeychainStore.swift index fb1151110..b20904c98 100644 --- a/AdamantShared/Services/KeychainStore.swift +++ b/AdamantShared/Services/KeychainStore.swift @@ -74,7 +74,6 @@ class KeychainStore: SecuredStore { NotificationCenter.default.post(name: Notification.Name.SecuredStore.securedStorePurged, object: self) } - // MARK: - Tools private static func encrypt(string: String, password: String, encoding: String.Encoding = .utf8) -> String? { diff --git a/AdamantShared/View/WarningView.swift b/AdamantShared/View/WarningView.swift index db101b98a..7b2997a2d 100644 --- a/AdamantShared/View/WarningView.swift +++ b/AdamantShared/View/WarningView.swift @@ -22,7 +22,7 @@ class WarningView: UIView { "😯", "😣", "😖", - "🤕", + "🤕" ] func setRandomEmoji() { diff --git a/AdamantTests/AdamantUriBuilding.swift b/AdamantTests/AdamantUriBuilding.swift index bf23b5917..2b92b6170 100644 --- a/AdamantTests/AdamantUriBuilding.swift +++ b/AdamantTests/AdamantUriBuilding.swift @@ -35,7 +35,6 @@ class AdamantUriBuilding: XCTestCase { } } - // MARK: - Addresses func testEncodeAddress() { let address = "U123456789012345" diff --git a/AdamantTests/Core/JSAdamantCore.swift b/AdamantTests/Core/JSAdamantCore.swift index 29b39d045..6211ce8d9 100644 --- a/AdamantTests/Core/JSAdamantCore.swift +++ b/AdamantTests/Core/JSAdamantCore.swift @@ -24,7 +24,6 @@ private enum JsFunction: String { } } - // MARK: - AdamantCoreError enum AdamantCoreError: Error { case errorLoadingJS(reason: String) @@ -32,7 +31,6 @@ enum AdamantCoreError: Error { case errorCallingFunction(function: String, jsError: String) } - // MARK: - AdamantCore /// You must load JavaScript before calling any methods. @@ -75,8 +73,8 @@ class JSAdamantCore : AdamantCore { } // MARK: 3. Catch JS errors - var jsError: JSValue? = nil - context.exceptionHandler = { context, value in + var jsError: JSValue? + context.exceptionHandler = { _, value in print("JSError: \(String(describing: value?.toString()))") jsError = value } @@ -96,7 +94,6 @@ class JSAdamantCore : AdamantCore { let bytes = JSObjectGetArrayBufferBytesPtr(contextRef, buffer, nil)! _ = SecRandomCopyBytes(kSecRandomDefault, count, bytes) - return JSValue(jsValueRef: array, in: context) } context.setObject(unsafeBitCast(crypto, to: AnyObject.self), forKeyedSubscript: "_randombytes" as NSCopying & NSObjectProtocol) @@ -118,7 +115,6 @@ class JSAdamantCore : AdamantCore { } } - // MARK: - Working with JS runtime extension JSAdamantCore { private func get(function: JsFunction) -> JSValue? { @@ -131,8 +127,8 @@ extension JSAdamantCore { return nil } - var jsError: JSValue? = nil - context.exceptionHandler = { context, value in + var jsError: JSValue? + context.exceptionHandler = { _, value in print("JSError: \(String(describing: value?.toString()))") jsError = value } @@ -165,7 +161,7 @@ extension JSAdamantCore { } // var jsError: JSValue? = nil - context.exceptionHandler = { ctx, exc in + context.exceptionHandler = { _, exc in print("JSError: \(String(describing: exc?.toString()))") // jsError = exc } @@ -177,7 +173,6 @@ extension JSAdamantCore { } } - // MARK: - Hash converters extension JSAdamantCore { private func convertToJsHash(_ hash: [UInt8]) -> JSValue { @@ -209,7 +204,6 @@ extension JSAdamantCore { } } - // MARK: - Keys extension JSAdamantCore { func createKeypairFor(rawHash: [UInt8]) -> Keypair? { @@ -261,8 +255,6 @@ extension JSAdamantCore { } } - - // MARK: - Transactions extension JSAdamantCore { func sign(transaction t: SignableTransaction, senderId: String, keypair: Keypair) -> String? { @@ -306,7 +298,6 @@ extension JSAdamantCore { } } - // MARK: - Messages extension JSAdamantCore { func encodeMessage(_ message: String, recipientPublicKey publicKey: String, privateKey privateKeyHex: String) -> (message: String, nonce: String)? { diff --git a/AdamantTests/Core/JSAdamantCoreTests.swift b/AdamantTests/Core/JSAdamantCoreTests.swift index bd515222d..0405b93f8 100644 --- a/AdamantTests/Core/JSAdamantCoreTests.swift +++ b/AdamantTests/Core/JSAdamantCoreTests.swift @@ -29,7 +29,6 @@ class JSAdamantCoreTests: XCTestCase { self.core = core } - func testHashForPassphrase() { let passphrase = "process gospel angry height between flat always clock suit refuse shove verb" let hash = "9001490b166816af75a15a3e2b0174bfe3be3dfaa63147b4f780ed3ab90ffeab" @@ -104,7 +103,6 @@ class JSAdamantCoreTests: XCTestCase { XCTAssertEqual(freshMessage, decodedMessage) } - // MARK: - Performance func testPerformanceHashForPassphrase() { diff --git a/AdamantTests/Core/JSModels.swift b/AdamantTests/Core/JSModels.swift index a71ae8ff6..189e61263 100644 --- a/AdamantTests/Core/JSModels.swift +++ b/AdamantTests/Core/JSModels.swift @@ -32,7 +32,6 @@ import JavaScriptCore } } - // MARK: - Transaction Asset @objc protocol JSAssetProtocol: JSExport { @@ -47,7 +46,6 @@ import JavaScriptCore dynamic var votes: [String]? } - // MARK: - Chat @objc protocol JSChatProtocol: JSExport { @@ -68,7 +66,6 @@ import JavaScriptCore } } - // MARK: - Store @objc protocol JSStateProtocol: JSExport { @@ -89,7 +86,6 @@ import JavaScriptCore } } - // MARK: - Transaction @objc protocol JSTransactionProtocol: JSExport { diff --git a/BitcoinKit/Sources/BitcoinKit/Scripts/AddressConverter.swift b/BitcoinKit/Sources/BitcoinKit/Scripts/AddressConverter.swift index 365ae11df..1bb84f171 100644 --- a/BitcoinKit/Sources/BitcoinKit/Scripts/AddressConverter.swift +++ b/BitcoinKit/Sources/BitcoinKit/Scripts/AddressConverter.swift @@ -15,7 +15,6 @@ class AddressConverter { case wrongAddressPrefix } - public static func extract(from signatureScript: Data, with network: Network) -> Address? { var payload: Data? var validScriptType: ScriptType = ScriptType.unknown diff --git a/BitcoinKit/Sources/BitcoinKitPrivate/BitcoinKit.Private.swift b/BitcoinKit/Sources/BitcoinKitPrivate/BitcoinKit.Private.swift index f55fdc521..459e12ab9 100644 --- a/BitcoinKit/Sources/BitcoinKitPrivate/BitcoinKit.Private.swift +++ b/BitcoinKit/Sources/BitcoinKitPrivate/BitcoinKit.Private.swift @@ -67,7 +67,6 @@ public class _Key { } let group = EC_KEY_get0_group(key) - let prv = BN_new() defer { BN_free(prv) @@ -87,7 +86,7 @@ public class _Key { if compression { EC_KEY_set_conv_form(key, POINT_CONVERSION_COMPRESSED) - var ptr: UnsafeMutablePointer? = nil + var ptr: UnsafeMutablePointer? let length = i2o_ECPublicKey(key, &ptr) return Data(bytes: ptr!, count: Int(length)) } else { @@ -285,7 +284,7 @@ public class _Crypto { throw CryptoError.publicKeyParseFailed } - guard message.withUnsafeBytes ({ secp256k1_ecdsa_verify(ctx, signaturePointer, $0, pubkeyPointer) }) == 1 else { + guard message.withUnsafeBytes({ secp256k1_ecdsa_verify(ctx, signaturePointer, $0, pubkeyPointer) }) == 1 else { return false } diff --git a/LiskKit/Package.swift b/LiskKit/Package.swift index 932db9ff7..b0800a56f 100644 --- a/LiskKit/Package.swift +++ b/LiskKit/Package.swift @@ -12,7 +12,7 @@ let package = Package( products: [ .library( name: "LiskKit", - targets: ["LiskKit"]), + targets: ["LiskKit"]) ], dependencies: [ .package(name: "Sodium", url: "https://github.com/jedisct1/swift-sodium.git", from: "0.9.1"), diff --git a/LiskKit/Sources/API/Node/Responses/NodeConstantsResponse.swift b/LiskKit/Sources/API/Node/Responses/NodeConstantsResponse.swift index f852204a3..06782e875 100644 --- a/LiskKit/Sources/API/Node/Responses/NodeConstantsResponse.swift +++ b/LiskKit/Sources/API/Node/Responses/NodeConstantsResponse.swift @@ -14,4 +14,3 @@ extension Node { public let data: NodeStatusModel } } - diff --git a/LiskKit/Sources/API/Transactions/LocalTransaction.swift b/LiskKit/Sources/API/Transactions/LocalTransaction.swift index 4d3eb869d..f6c269a1b 100644 --- a/LiskKit/Sources/API/Transactions/LocalTransaction.swift +++ b/LiskKit/Sources/API/Transactions/LocalTransaction.swift @@ -35,7 +35,7 @@ internal func writeUInt32(_ value: UInt32) -> [UInt8] { result.append(UInt8(value)) return result -}; +} internal func writeUInt64(_ value: UInt64) -> [UInt8] { var result = [UInt8]() @@ -49,10 +49,10 @@ internal func writeUInt64(_ value: UInt64) -> [UInt8] { result.append(UInt8(value)) return result -}; +} extension Data { - var bytes: Array { + var bytes: [UInt8] { let count = self.count / MemoryLayout.size var byteArray = [UInt8](repeating: 0, count: count) self.copyBytes(to: &byteArray, count:count) @@ -441,7 +441,6 @@ extension LocalTransaction { } } - protocol BinaryConvertible { static func +(lhs: Data, rhs: Self) -> Data static func +=(lhs: inout Data, rhs: Self) diff --git a/LiskKit/Sources/API/Transactions/Models/TransactionModel.swift b/LiskKit/Sources/API/Transactions/Models/TransactionModel.swift index 1e758d974..85c56358a 100644 --- a/LiskKit/Sources/API/Transactions/Models/TransactionModel.swift +++ b/LiskKit/Sources/API/Transactions/Models/TransactionModel.swift @@ -65,7 +65,7 @@ extension Transactions { hasher.combine(id) } - public mutating func updateConfirmations(value: UInt64){ + public mutating func updateConfirmations(value: UInt64) { confirmations = value } } diff --git a/LiskKit/Sources/Core/APIClient.swift b/LiskKit/Sources/Core/APIClient.swift index a2ec41b64..a73007e2a 100644 --- a/LiskKit/Sources/Core/APIClient.swift +++ b/LiskKit/Sources/Core/APIClient.swift @@ -64,7 +64,7 @@ public struct APIClient { "User-Agent": options.nethash.userAgent, "nethash": options.nethash.nethash, "version": options.nethash.version, - "minVersion": options.nethash.minVersion, + "minVersion": options.nethash.minVersion ] } diff --git a/LiskKit/Sources/Crypto/BytePacker.swift b/LiskKit/Sources/Crypto/BytePacker.swift index b01232f3f..7b0daa714 100644 --- a/LiskKit/Sources/Crypto/BytePacker.swift +++ b/LiskKit/Sources/Crypto/BytePacker.swift @@ -23,7 +23,7 @@ internal struct BytePacker { static func pack( _ value: T, byteOrder: ByteOrder) -> [UInt8] { var value = value // inout works only for var not let types let valueByteArray = withUnsafePointer(to: &value) { - Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: UInt8.self, capacity: 1){$0}, count: MemoryLayout.size)) + Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: UInt8.self, capacity: 1) {$0}, count: MemoryLayout.size)) } return (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed() } diff --git a/LiskKit/Sources/Crypto/Crypto.swift b/LiskKit/Sources/Crypto/Crypto.swift index 54e672519..03779ee0c 100644 --- a/LiskKit/Sources/Crypto/Crypto.swift +++ b/LiskKit/Sources/Crypto/Crypto.swift @@ -89,7 +89,7 @@ public struct Crypto { } internal static func convertUIntArray(_ array: [UInt], _ from: UInt, _ to: UInt) -> [UInt] { - let maxValue: UInt = (1 << to) - 1; + let maxValue: UInt = (1 << to) - 1 var accumulator: UInt = 0 var bits: UInt = 0 var result = [UInt]() @@ -153,7 +153,6 @@ public struct Crypto { let message = message.hexBytes() let publicKey = publicKey.hexBytes() - guard .SUCCESS == crypto_sign_verify_detached( signature, message, @@ -296,7 +295,7 @@ public class KeyPair { public func sign(_ message: [UInt8]) -> [UInt8] { var signature = [UInt8](repeating: 0, count: Int(crypto_sign_bytes())) - guard .SUCCESS == crypto_sign_detached ( + guard .SUCCESS == crypto_sign_detached( &signature, nil, message, UInt64(message.count), diff --git a/LiskKit/Sources/Crypto/SHA256.swift b/LiskKit/Sources/Crypto/SHA256.swift index b6bd0e790..34f14d4a2 100644 --- a/LiskKit/Sources/Crypto/SHA256.swift +++ b/LiskKit/Sources/Crypto/SHA256.swift @@ -182,7 +182,7 @@ public final class SHA256 { } } -// MARK:- Helpers +// MARK: - Helpers private extension UInt64 { /// Converts the 64 bit integer into an array of single byte integers. diff --git a/LiskKit/Tests/API/Transactions/TransactionsTransferTests.swift b/LiskKit/Tests/API/Transactions/TransactionsTransferTests.swift index f3177d065..5b2d1d969 100644 --- a/LiskKit/Tests/API/Transactions/TransactionsTransferTests.swift +++ b/LiskKit/Tests/API/Transactions/TransactionsTransferTests.swift @@ -18,6 +18,6 @@ class TransactionsTransferTests: LiskTestCase { func testTestnetSendWithFunds() { let transactions = Transactions(client: testNetClient) - let _ = tryRequest { transactions.transfer(lsk: 0.1, to: exampleAddress, passphrase: testSecret, completionHandler: $0) } + _ = tryRequest { transactions.transfer(lsk: 0.1, to: exampleAddress, passphrase: testSecret, completionHandler: $0) } } } diff --git a/LiskKit/Tests/LiskTestCase.swift b/LiskKit/Tests/LiskTestCase.swift index e89b2793e..0ab75da68 100644 --- a/LiskKit/Tests/LiskTestCase.swift +++ b/LiskKit/Tests/LiskTestCase.swift @@ -40,7 +40,7 @@ class LiskTestCase: XCTestCase { var result: R? - block() { response in + block { response in switch response { case .success(let r): result = r @@ -57,7 +57,7 @@ class LiskTestCase: XCTestCase { func tryRequestError(_ block: (@escaping (Response) -> Void) -> Void) -> APIError { let expectation = XCTestExpectation() var error: APIError? - block() { response in + block { response in switch response { case .success: XCTFail("Expected an error response, request was succeeded") diff --git a/MessageNotificationContentExtension/NotificationViewController.swift b/MessageNotificationContentExtension/NotificationViewController.swift index e70b4d049..065d60b97 100644 --- a/MessageNotificationContentExtension/NotificationViewController.swift +++ b/MessageNotificationContentExtension/NotificationViewController.swift @@ -40,10 +40,10 @@ class NotificationViewController: UIViewController, UNNotificationContentExtensi func didReceive(_ notification: UNNotification) { // MARK: 0. Necessary services let avatarService = AdamantAvatarService() - var keychainStore: KeychainStore? = nil - var extensionApi: ExtensionsApi? = nil - var nativeCore: NativeAdamantCore? = nil - var keypair: Keypair? = nil + var keychainStore: KeychainStore? + var extensionApi: ExtensionsApi? + var nativeCore: NativeAdamantCore? + var keypair: Keypair? // MARK: 1. Get the transaction let trs: Transaction? diff --git a/NotificationServiceExtension/NotificationService.swift b/NotificationServiceExtension/NotificationService.swift index faf73c83f..edd227a24 100644 --- a/NotificationServiceExtension/NotificationService.swift +++ b/NotificationServiceExtension/NotificationService.swift @@ -72,7 +72,7 @@ class NotificationService: UNNotificationServiceExtension { let partnerAddress: String let partnerPublicKey: String let partnerName: String? - var decodedMessage: String? = nil + var decodedMessage: String? if transaction.senderId == pushRecipient { partnerAddress = transaction.recipientId @@ -168,8 +168,6 @@ class NotificationService: UNNotificationServiceExtension { } bestAttemptContent.userInfo[AdamantNotificationUserInfoKeys.decodedMessage] = decodedMessage - - contentHandler(bestAttemptContent) } diff --git a/TransferNotificationContentExtension/NotificationViewController.swift b/TransferNotificationContentExtension/NotificationViewController.swift index a88803be2..646ec794a 100644 --- a/TransferNotificationContentExtension/NotificationViewController.swift +++ b/TransferNotificationContentExtension/NotificationViewController.swift @@ -103,7 +103,7 @@ class NotificationViewController: UIViewController, UNNotificationContentExtensi let keychain = KeychainStore() let core = NativeAdamantCore() let avatarService = AdamantAvatarService() - var api: ExtensionsApi? = nil + var api: ExtensionsApi? guard let passphrase = keychain.get(passphraseStoreKey), let keypair = core.createKeypairFor(passphrase: passphrase) else { showError()