From 3f6fb5e20d77fa8d631f5b03ffd57b754e632e9e Mon Sep 17 00:00:00 2001 From: Fernando Bunn Date: Mon, 4 Apr 2022 12:23:10 +0200 Subject: [PATCH] Improve swift style + swiftlint (#1092) Task/Issue URL: https://app.asana.com/0/0/1201986385932308/f Description: Implement style guide changes Update swift lint Fork style from RW repo with some added changes --- .swiftlint.yml | 53 +- AtbUITests/AtbIntegrationTests.swift | 2 +- Core/APIRequest.swift | 2 +- Core/BookmarkObjects.swift | 2 +- Core/BookmarksCoreDataStorage.swift | 4 +- Core/Database.swift | 2 +- Core/PartiallyRoundedRectangleView.swift | 6 +- Core/PrivacyPractices.swift | 2 +- Core/WebCacheManager.swift | 2 +- .../ActionSheetDaxDialogViewController.swift | 2 +- .../AddOrEditBookmarkViewController.swift | 2 +- DuckDuckGo/AppRatingPrompt.swift | 4 +- DuckDuckGo/AutocompleteViewController.swift | 2 +- DuckDuckGo/BookmarksDataSource.swift | 3 +- DuckDuckGo/BrowserChromeManager.swift | 2 +- .../BrowsingMenuViewController.swift | 4 +- DuckDuckGo/DirectoryMonitor.swift | 6 +- DuckDuckGo/DownloadListRepresentable.swift | 4 +- .../DownloadsListSectioningHelper.swift | 4 +- DuckDuckGo/FavoritesOverlay.swift | 2 +- DuckDuckGo/FileSizeDebugViewController.swift | 4 +- DuckDuckGo/FindInPageUserScript.swift | 2 +- DuckDuckGo/FindInPageView.swift | 2 + .../FullscreenDaxDialogViewController.swift | 2 +- DuckDuckGo/LaunchTabNotification.swift | 2 +- ...eDisplayableCertificateBuilderDriver.swift | 4 +- DuckDuckGo/OnboardingViewController.swift | 2 +- DuckDuckGo/OngoingDownloadRow.swift | 2 +- DuckDuckGo/OngoingDownloadRowViewModel.swift | 6 +- ...PreserveLoginsSettingsViewController.swift | 6 +- ...ProtectionEncryptionDetailController.swift | 5 +- .../PrivacyProtectionOverviewController.swift | 2 +- ...PrivacyProtectionPracticesController.swift | 7 +- ...PrivacyProtectionScoreCardController.swift | 2 + ...yProtectionTrackerNetworksController.swift | 2 +- DuckDuckGo/ProgressView.swift | 1 + DuckDuckGo/RootDebugViewController.swift | 8 +- DuckDuckGo/SpeechRecognizer.swift | 2 +- DuckDuckGo/TabViewController.swift | 2 +- DuckDuckGo/TabsBarCell.swift | 2 +- DuckDuckGo/Theme.swift | 2 +- DuckDuckGo/WidgetEducationHomeMessage.swift | 2 +- DuckDuckGoTests/APIRequestTests.swift | 2 + .../AppConfigurationFetchTests.swift | 2 + .../AppHTTPSUpgradeStoreTests.swift | 3 + DuckDuckGoTests/AppRatingPromptTests.swift | 2 +- DuckDuckGoTests/AppUserDefaultsTests.swift | 1 + .../AppVersionExtensionTests.swift | 2 + DuckDuckGoTests/AppVersionTests.swift | 2 + .../AutoClearSettingsScreenTests.swift | 6 +- DuckDuckGoTests/AutoClearTests.swift | 2 + .../BookmarksCachingSearchTests.swift | 6 +- DuckDuckGoTests/DatabaseMigrationTests.swift | 6 +- .../DaxDialogsBrowsingSpecTests.swift | 2 +- ...ainsProtectionUserDefaultsStoreTests.swift | 2 + DuckDuckGoTests/DownloadManagerTests.swift | 4 +- DuckDuckGoTests/DownloadTests.swift | 4 +- DuckDuckGoTests/HomeRowReminderTests.swift | 2 + DuckDuckGoTests/InitHelpers.swift | 3 +- DuckDuckGoTests/LargeOmniBarStateTests.swift | 4 + DuckDuckGoTests/NetworkLeaderboardTests.swift | 2 + DuckDuckGoTests/PreserveLoginsTests.swift | 2 + .../SettingsViewControllerTests.swift | 3 + DuckDuckGoTests/SiteRatingTests.swift | 4 +- DuckDuckGoTests/SmallOmniBarStateTests.swift | 4 + DuckDuckGoTests/StatisticsLoaderTests.swift | 2 + .../StatisticsUserDefaultsTests.swift | 2 + DuckDuckGoTests/TabPreviewsSourceTests.swift | 4 + .../TabsModelPersistenceExtensionTests.swift | 2 + ...rDefaultsHomeRowReminderStorageTests.swift | 2 + DuckDuckGoTests/VariantManagerTests.swift | 6 +- FingerprintingUITests/FingerprintUITest.swift | 3 + Widgets/Widgets.swift | 14 +- styleguide/STYLEGUIDE.md | 1073 ++++++++++++++++- 74 files changed, 1241 insertions(+), 116 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index d88cafb55a..148443ca05 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,21 +1,56 @@ disabled_rules: - - trailing_whitespace + - discarded_notification_center_observer + - notification_center_detachment + - orphaned_doc_comment + - todo + - unused_capture_list + +opt_in_rules: + - closure_end_indentation + - closure_spacing + - colon + - overridden_super_call + - unused_import + - fatal_error_message + +force_cast: warning +force_try: warning +legacy_hashing: error -# Rule Config -line_length: - warning: 150 - ignores_comments: true identifier_name: min_length: 1 max_length: warning: 40 error: 60 + excluded: + - i + - id + - x + - y + - z + +line_length: + warning: 150 + ignores_urls: true + ignores_function_declarations: true + ignores_comments: true + +vertical_whitespace: + max_empty_lines: 2 + +trailing_whitespace: + ignores_empty_lines: true + ignores_comments: true + +private_over_fileprivate: + validate_extensions: true + type_name: - min_length: 3 - max_length: - warning: 80 - error: 100 + min_length: 3 + max_length: + warning: 80 + error: 100 # General Config excluded: diff --git a/AtbUITests/AtbIntegrationTests.swift b/AtbUITests/AtbIntegrationTests.swift index f340d5e9c9..c105761358 100644 --- a/AtbUITests/AtbIntegrationTests.swift +++ b/AtbUITests/AtbIntegrationTests.swift @@ -137,7 +137,7 @@ class AtbIntegrationTests: XCTestCase { } -fileprivate extension HttpRequest { +private extension HttpRequest { func queryParam(_ named: String) -> String? { return queryParams.first(where: { $0.0 == named })?.1 diff --git a/Core/APIRequest.swift b/Core/APIRequest.swift index a44dc16b5f..7dce0ebebb 100644 --- a/Core/APIRequest.swift +++ b/Core/APIRequest.swift @@ -88,7 +88,7 @@ public class APIRequest { if let error = error { completion(nil, error) - } else if let error = httpResponse?.validateStatusCode(statusCode: 200..<300) { + } else if let error = httpResponse?.validateStatusCode(statusCode: 200..<300) { completion(nil, error) } else { var etag = httpResponse?.headerValue(for: APIHeaders.Name.etag) diff --git a/Core/BookmarkObjects.swift b/Core/BookmarkObjects.swift index 34496756fe..be67af7928 100644 --- a/Core/BookmarkObjects.swift +++ b/Core/BookmarkObjects.swift @@ -34,7 +34,7 @@ private struct Constants { public protocol Bookmark: BookmarkItem { var url: URL? { get set } - var displayTitle: String? { get } + var displayTitle: String? { get } } public extension Bookmark { diff --git a/Core/BookmarksCoreDataStorage.swift b/Core/BookmarksCoreDataStorage.swift index c6f3438a8c..2f2babd627 100644 --- a/Core/BookmarksCoreDataStorage.swift +++ b/Core/BookmarksCoreDataStorage.swift @@ -132,7 +132,7 @@ public class BookmarksCoreDataStorage { context.perform { handler(context) self.storeLoadedCondition.resolve() - } + } } } } @@ -422,7 +422,7 @@ extension BookmarksCoreDataStorage { loadStore() } - public func favoritesUncachedForWidget(completion: @escaping ([BookmarkManagedObject]) -> Void) { + public func favoritesUncachedForWidget(completion: @escaping ([BookmarkManagedObject]) -> Void) { Task { guard await hasTopLevelFolder() else { completion([]) diff --git a/Core/Database.swift b/Core/Database.swift index df48cc7140..d89ddf6bcf 100644 --- a/Core/Database.swift +++ b/Core/Database.swift @@ -122,5 +122,5 @@ private class DDGPersistentContainer: NSPersistentContainer { override public class func defaultDirectoryURL() -> URL { return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Database.Constants.databaseGroupID)! - } + } } diff --git a/Core/PartiallyRoundedRectangleView.swift b/Core/PartiallyRoundedRectangleView.swift index 7929bdb303..81ad67f80e 100644 --- a/Core/PartiallyRoundedRectangleView.swift +++ b/Core/PartiallyRoundedRectangleView.swift @@ -47,9 +47,9 @@ public class PartiallyRoundedRectangleView: UIView { override public func layoutSubviews() { super.layoutSubviews() var corners = UIRectCorner() - if topLeftCorner { corners.insert(.topLeft) } - if topRightCorner { corners.insert(.topRight) } - if bottomLeftCorner { corners.insert(.bottomLeft) } + if topLeftCorner { corners.insert(.topLeft) } + if topRightCorner { corners.insert(.topRight) } + if bottomLeftCorner { corners.insert(.bottomLeft) } if bottomRightCorner { corners.insert(.bottomRight) } round(corners: corners, radius: cornerRadius) } diff --git a/Core/PrivacyPractices.swift b/Core/PrivacyPractices.swift index 83bd698ea9..fd1dc989f1 100644 --- a/Core/PrivacyPractices.swift +++ b/Core/PrivacyPractices.swift @@ -72,7 +72,7 @@ public class PrivacyPractices { func findPractice(forHost host: String) -> Practice { guard let domain = tld.domain(host) else { return Constants.unknown } - guard let term = termsOfServiceStore.terms[domain] else { return Constants.unknown} + guard let term = termsOfServiceStore.terms[domain] else { return Constants.unknown } let entityScore = entityScores[entityMapping.findEntity(forHost: domain)?.displayName ?? ""] return Practice(score: entityScore ?? term.derivedScore, summary: term.summary, diff --git a/Core/WebCacheManager.swift b/Core/WebCacheManager.swift index 9aed12f766..ec1886cca1 100644 --- a/Core/WebCacheManager.swift +++ b/Core/WebCacheManager.swift @@ -113,7 +113,7 @@ public class WebCacheManager { cookieStore.getAllCookies { cookies in let group = DispatchGroup() cookies.forEach { cookie in - if domains.contains(where: { self.isCookie(cookie, matchingDomain: $0)}) { + if domains.contains(where: { self.isCookie(cookie, matchingDomain: $0) }) { group.enter() cookieStore.delete(cookie) { group.leave() diff --git a/DuckDuckGo/ActionSheetDaxDialogViewController.swift b/DuckDuckGo/ActionSheetDaxDialogViewController.swift index 81a60bcae6..f150df9f4e 100644 --- a/DuckDuckGo/ActionSheetDaxDialogViewController.swift +++ b/DuckDuckGo/ActionSheetDaxDialogViewController.swift @@ -74,7 +74,7 @@ class ActionSheetDaxDialogViewController: UIViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) - containerHeight.constant = daxDialogViewController?.calculateHeight() ?? 0 + containerHeight.constant = daxDialogViewController?.calculateHeight() ?? 0 } override func viewDidAppear(_ animated: Bool) { diff --git a/DuckDuckGo/AddOrEditBookmarkViewController.swift b/DuckDuckGo/AddOrEditBookmarkViewController.swift index 2172c85124..e0dcf8f9db 100644 --- a/DuckDuckGo/AddOrEditBookmarkViewController.swift +++ b/DuckDuckGo/AddOrEditBookmarkViewController.swift @@ -105,7 +105,7 @@ class AddOrEditBookmarkViewController: UIViewController { } } -extension AddOrEditBookmarkViewController: BookmarkOrFavoriteDetailsDataSourceDelegate { +extension AddOrEditBookmarkViewController: BookmarkOrFavoriteDetailsDataSourceDelegate { func bookmarkOrFavoriteDetailsDataSource(_ dataSource: BookmarkOrFavoriteDetailsDataSource, textFieldDidChangeWithTitleText titleText: String?, diff --git a/DuckDuckGo/AppRatingPrompt.swift b/DuckDuckGo/AppRatingPrompt.swift index e42909ee80..31c3f7030b 100644 --- a/DuckDuckGo/AppRatingPrompt.swift +++ b/DuckDuckGo/AppRatingPrompt.swift @@ -42,7 +42,7 @@ class AppRatingPrompt { func registerUsage(onDate date: Date = Date()) { if !date.isSameDay(storage.lastAccess) { storage.uniqueAccessDays += 1 - } + } storage.lastAccess = date } @@ -65,7 +65,7 @@ class AppRatingPromptCoreDataStorage: AppRatingPromptStorage { set { entity().lastAccess = newValue - try? context.save() + try? context.save() } } diff --git a/DuckDuckGo/AutocompleteViewController.swift b/DuckDuckGo/AutocompleteViewController.swift index 4282864951..135040441d 100644 --- a/DuckDuckGo/AutocompleteViewController.swift +++ b/DuckDuckGo/AutocompleteViewController.swift @@ -153,7 +153,7 @@ class AutocompleteViewController: UIViewController { strongSelf.bookmarksSearch.search(query: query) { matches in let notQueryMatches = matches.filter { $0.url?.absoluteString != query } let filteredMatches = notQueryMatches.filter { $0.displayTitle != nil }.prefix(Constants.maxLocalItems) - let localSuggestions = filteredMatches.map { Suggestion(source: .local, suggestion: $0.displayTitle!, url: $0.url)} + let localSuggestions = filteredMatches.map { Suggestion(source: .local, suggestion: $0.displayTitle!, url: $0.url) } guard let suggestions = suggestions, error == nil else { os_log("%s", log: generalLog, type: .debug, error?.localizedDescription ?? "Failed to retrieve suggestions") diff --git a/DuckDuckGo/BookmarksDataSource.swift b/DuckDuckGo/BookmarksDataSource.swift index 1f3bffc2cd..8be994208e 100644 --- a/DuckDuckGo/BookmarksDataSource.swift +++ b/DuckDuckGo/BookmarksDataSource.swift @@ -139,8 +139,7 @@ class DefaultBookmarksDataSource: BookmarksDataSource, MainBookmarksViewDataSour bookmarksManager.convertFavoriteToBookmark(item.objectID, newIndex: destinationIndexPath.row) } else if sourceIndexPath.section == 1 && destinationIndexPath.section == 0 { guard let bookmark = item as? Bookmark else { - // Folders aren't allowed in favourites. We shouldn't be able to get here - fatalError() + fatalError("Folders aren't allowed in favorites. We shouldn't be able to get here") } bookmarksManager.convertBookmarkToFavorite(bookmark.objectID, newIndex: destinationIndexPath.row) } diff --git a/DuckDuckGo/BrowserChromeManager.swift b/DuckDuckGo/BrowserChromeManager.swift index f482da4c21..c9e2796862 100644 --- a/DuckDuckGo/BrowserChromeManager.swift +++ b/DuckDuckGo/BrowserChromeManager.swift @@ -333,7 +333,7 @@ private class BarsAnimator { } } -fileprivate extension UIScrollView { +private extension UIScrollView { /// Calculate Y-axis content offset corresponding to very bottom of the scroll area var contentOffsetYAtBottom: CGFloat { diff --git a/DuckDuckGo/BrowsingMenu/BrowsingMenuViewController.swift b/DuckDuckGo/BrowsingMenu/BrowsingMenuViewController.swift index 652eea78fd..9ab92ea31c 100644 --- a/DuckDuckGo/BrowsingMenu/BrowsingMenuViewController.swift +++ b/DuckDuckGo/BrowsingMenu/BrowsingMenuViewController.swift @@ -307,14 +307,14 @@ extension BrowsingMenuViewController: UITableViewDataSource { switch menuEntries[indexPath.row] { case .regular(let name, let accessibilityLabel, let image, let showNotificationDot, _): guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowsingMenuEntryViewCell", for: indexPath) as? BrowsingMenuEntryViewCell else { - fatalError() + fatalError("Cell should be dequeued") } cell.configure(image: image, label: name, accessibilityLabel: accessibilityLabel, theme: theme, showNotificationDot: showNotificationDot) return cell case .separator: guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowsingMenuSeparatorViewCell", for: indexPath) as? BrowsingMenuSeparatorViewCell else { - fatalError() + fatalError("Cell should be dequeued") } cell.separator.backgroundColor = theme.browsingMenuSeparatorColor diff --git a/DuckDuckGo/DirectoryMonitor.swift b/DuckDuckGo/DirectoryMonitor.swift index 0af881c6f5..7b3b3e7654 100644 --- a/DuckDuckGo/DirectoryMonitor.swift +++ b/DuckDuckGo/DirectoryMonitor.swift @@ -67,7 +67,7 @@ class DirectoryMonitor { } func start() throws { - guard case .stopped = state else { fatalError() } + guard case .stopped = state else { fatalError("Should only start stopped state") } directoryContents = DirectoryMonitor.contents(of: directory) @@ -110,7 +110,7 @@ class DirectoryMonitor { } private func debounceTimerDidFire() { - guard case .debounce(let source, let timer) = state else { fatalError() } + guard case .debounce(let source, let timer) = state else { fatalError("state should be .debounce") } timer.invalidate() state = .started(source: source) @@ -142,7 +142,7 @@ class DirectoryMonitor { } } -fileprivate extension DirectoryMonitor.State { +private extension DirectoryMonitor.State { var isRunning: Bool { switch self { case .stopped: return false diff --git a/DuckDuckGo/DownloadListRepresentable.swift b/DuckDuckGo/DownloadListRepresentable.swift index 8089bffaaf..6de7772d3d 100644 --- a/DuckDuckGo/DownloadListRepresentable.swift +++ b/DuckDuckGo/DownloadListRepresentable.swift @@ -40,12 +40,12 @@ struct AnyDownloadListRepresentable: DownloadListRepresentable, Comparable { self.wrappedRepresentable = representable } - public var id: String { filename} + public var id: String { filename } var filename: String { wrappedRepresentable.filename } var creationDate: Date { wrappedRepresentable.creationDate } var fileSize: Int { wrappedRepresentable.fileSize } var type: DownloadListRepresentableType { wrappedRepresentable.type } - var filePath: String { wrappedRepresentable.filePath} + var filePath: String { wrappedRepresentable.filePath } static func < (lhs: AnyDownloadListRepresentable, rhs: AnyDownloadListRepresentable) -> Bool { lhs.creationDate < rhs.creationDate diff --git a/DuckDuckGo/DownloadsListSectioningHelper.swift b/DuckDuckGo/DownloadsListSectioningHelper.swift index ceb5dbe9a2..46a1c4454c 100644 --- a/DuckDuckGo/DownloadsListSectioningHelper.swift +++ b/DuckDuckGo/DownloadsListSectioningHelper.swift @@ -95,10 +95,10 @@ class DownloadsListSectioningHelper { switch downloadRepresentable.type { case .ongoing: - guard let download = downloadRepresentable.wrappedRepresentable as? Download else { fatalError() } + guard let download = downloadRepresentable.wrappedRepresentable as? Download else { fatalError("Ongoing download should be Download") } row = OngoingDownloadRowViewModel(download: download) case .complete: - guard let url = downloadRepresentable.wrappedRepresentable as? URL else { fatalError() } + guard let url = downloadRepresentable.wrappedRepresentable as? URL else { fatalError("Complete download should be URL") } row = CompleteDownloadRowViewModel(fileURL: url) } diff --git a/DuckDuckGo/FavoritesOverlay.swift b/DuckDuckGo/FavoritesOverlay.swift index 46cd4f5127..b712281ba6 100644 --- a/DuckDuckGo/FavoritesOverlay.swift +++ b/DuckDuckGo/FavoritesOverlay.swift @@ -86,7 +86,7 @@ class FavoritesOverlay: UIViewController { } @objc private func keyboardDidShow(notification: NSNotification) { - guard !AppWidthObserver.shared.isLargeWidth else { return } + guard !AppWidthObserver.shared.isLargeWidth else { return } guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } let keyboardSize = keyboardFrame.size let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height + Constants.margin * 2, right: 0.0) diff --git a/DuckDuckGo/FileSizeDebugViewController.swift b/DuckDuckGo/FileSizeDebugViewController.swift index 85a3b96046..c6a9a72817 100644 --- a/DuckDuckGo/FileSizeDebugViewController.swift +++ b/DuckDuckGo/FileSizeDebugViewController.swift @@ -27,7 +27,7 @@ struct FileItem { let isDirectory: Bool let size: Int? - var isEmpty: Bool { (size ?? 0) == 0} + var isEmpty: Bool { (size ?? 0) == 0 } } class FileSizeDebugViewController: UITableViewController { @@ -160,7 +160,7 @@ class FileSizeDebugViewController: UITableViewController { } } -fileprivate extension URL { +private extension URL { var isDirectory: Bool { let urlForDirectory = (try? resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false diff --git a/DuckDuckGo/FindInPageUserScript.swift b/DuckDuckGo/FindInPageUserScript.swift index 86dd6c6956..075a5548aa 100644 --- a/DuckDuckGo/FindInPageUserScript.swift +++ b/DuckDuckGo/FindInPageUserScript.swift @@ -40,5 +40,5 @@ public class FindInPageUserScript: NSObject, UserScript { let currentResult = dict["currentResult"] as? Int let totalResults = dict["totalResults"] as? Int findInPage?.update(currentResult: currentResult, totalResults: totalResults) - } + } } diff --git a/DuckDuckGo/FindInPageView.swift b/DuckDuckGo/FindInPageView.swift index 29f3a5312f..66f7965dc8 100644 --- a/DuckDuckGo/FindInPageView.swift +++ b/DuckDuckGo/FindInPageView.swift @@ -40,6 +40,8 @@ class FindInPageView: UIView { weak var findInPage: FindInPage? override func awakeFromNib() { + super.awakeFromNib() + layer.shadowRadius = 1 layer.shadowOffset = CGSize(width: 0, height: -1.0 / UIScreen.main.scale) layer.shadowColor = UIColor.black.cgColor diff --git a/DuckDuckGo/FullscreenDaxDialogViewController.swift b/DuckDuckGo/FullscreenDaxDialogViewController.swift index e587b4fae8..b6b14042e2 100644 --- a/DuckDuckGo/FullscreenDaxDialogViewController.swift +++ b/DuckDuckGo/FullscreenDaxDialogViewController.swift @@ -160,7 +160,7 @@ extension TabViewController: FullscreenDaxDialogDelegate { } } -fileprivate extension DefaultDaxDialogsSettings { +private extension DefaultDaxDialogsSettings { var browsingDialogsSeenCount: String { let count = [ browsingMajorTrackingSiteShown, diff --git a/DuckDuckGo/LaunchTabNotification.swift b/DuckDuckGo/LaunchTabNotification.swift index 1f2accf674..eae5079c87 100644 --- a/DuckDuckGo/LaunchTabNotification.swift +++ b/DuckDuckGo/LaunchTabNotification.swift @@ -56,7 +56,7 @@ class LaunchTabNotification { } -fileprivate extension NSNotification.Name { +private extension NSNotification.Name { static let launchTab: NSNotification.Name = Notification.Name(rawValue: "com.duckduckgo.notification.launchTab") diff --git a/DuckDuckGo/NativeDisplayableCertificateBuilderDriver.swift b/DuckDuckGo/NativeDisplayableCertificateBuilderDriver.swift index 14f4270205..f7b817412d 100644 --- a/DuckDuckGo/NativeDisplayableCertificateBuilderDriver.swift +++ b/DuckDuckGo/NativeDisplayableCertificateBuilderDriver.swift @@ -45,7 +45,7 @@ class NativeDisplayableCertificateBuilderDriver: DisplayableCertificateBuilderDr } -fileprivate extension SecCertificate { +private extension SecCertificate { func toDisplayable() -> DisplayableCertificate { let displayable = DisplayableCertificate() @@ -85,7 +85,7 @@ fileprivate extension SecCertificate { } -fileprivate extension SecKey { +private extension SecKey { func toDisplayable() -> DisplayableKey { var key = DisplayableKey() diff --git a/DuckDuckGo/OnboardingViewController.swift b/DuckDuckGo/OnboardingViewController.swift index 2d881adb49..d08cd5696e 100644 --- a/DuckDuckGo/OnboardingViewController.swift +++ b/DuckDuckGo/OnboardingViewController.swift @@ -199,7 +199,7 @@ class OnboardingViewController: UIViewController, Onboarding { } override var shouldAutorotate: Bool { - return true + return true } } diff --git a/DuckDuckGo/OngoingDownloadRow.swift b/DuckDuckGo/OngoingDownloadRow.swift index 0e1a9e2bd5..086e42dfc5 100644 --- a/DuckDuckGo/OngoingDownloadRow.swift +++ b/DuckDuckGo/OngoingDownloadRow.swift @@ -20,7 +20,7 @@ import SwiftUI import Combine -struct OngoingDownloadRow: View { +struct OngoingDownloadRow: View { @ObservedObject var rowModel: OngoingDownloadRowViewModel var cancelButtonAction: () -> Void diff --git a/DuckDuckGo/OngoingDownloadRowViewModel.swift b/DuckDuckGo/OngoingDownloadRowViewModel.swift index 414dd4344c..4ed63fbe40 100644 --- a/DuckDuckGo/OngoingDownloadRowViewModel.swift +++ b/DuckDuckGo/OngoingDownloadRowViewModel.swift @@ -35,7 +35,7 @@ class OngoingDownloadRowViewModel: DownloadsListRowViewModel { private func subscribeToUpdates(from download: Download) { let totalSize = download.totalBytesExpectedToWrite - + download.$totalBytesWritten .throttle(for: .milliseconds(1000), scheduler: DispatchQueue.main, latest: true) .sink { [weak self] currentSize in @@ -47,11 +47,11 @@ class OngoingDownloadRowViewModel: DownloadsListRowViewModel { } else { self?.fileSize = UserText.downloadProgressMessageForUnknownTotalSize(currentSize: currentSizeString) } - }.store(in: &subscribers) + }.store(in: &subscribers) download.$totalBytesWritten .sink { [weak self] currentSize in self?.progress = Float(currentSize)/Float(totalSize) - }.store(in: &subscribers) + }.store(in: &subscribers) } } diff --git a/DuckDuckGo/PreserveLoginsSettingsViewController.swift b/DuckDuckGo/PreserveLoginsSettingsViewController.swift index 0060fa1b82..709c949af7 100644 --- a/DuckDuckGo/PreserveLoginsSettingsViewController.swift +++ b/DuckDuckGo/PreserveLoginsSettingsViewController.swift @@ -163,7 +163,7 @@ class PreserveLoginsSettingsViewController: UITableViewController { func createSwitchCell(forTableView tableView: UITableView, withTheme theme: Theme) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "SettingCell") as? PreserveLoginsSwitchCell else { - fatalError() + fatalError("Cell should be dequeued") } cell.label.textColor = theme.tableCellTextColor cell.toggle.onTintColor = theme.buttonTintColor @@ -175,7 +175,7 @@ class PreserveLoginsSettingsViewController: UITableViewController { func createDomainCell(forTableView tableView: UITableView, withTheme theme: Theme, forIndex index: Int) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DomainCell") as? PreserveLoginDomainCell else { - fatalError() + fatalError("Cell should be dequeued") } cell.label.textColor = theme.tableCellTextColor cell.faviconImage.loadFavicon(forDomain: model[index], usingCache: .bookmarks) @@ -253,7 +253,7 @@ class PreserveLoginDomainCell: UITableViewCell { } -fileprivate extension IndexPath { +private extension IndexPath { func isInSection(section: PreserveLoginsSettingsViewController.Section) -> Bool { return self.section == section.rawValue diff --git a/DuckDuckGo/PrivacyProtectionEncryptionDetailController.swift b/DuckDuckGo/PrivacyProtectionEncryptionDetailController.swift index 7e2463ebd1..fd1f637e6f 100644 --- a/DuckDuckGo/PrivacyProtectionEncryptionDetailController.swift +++ b/DuckDuckGo/PrivacyProtectionEncryptionDetailController.swift @@ -47,7 +47,8 @@ class PrivacyProtectionEncryptionDetailController: UIViewController { private var sections = [Section]() override func viewDidLoad() { - + super.viewDidLoad() + Pixel.fire(pixel: .privacyDashboardEncryption) initTableView() @@ -192,7 +193,7 @@ extension PrivacyProtectionEncryptionDetailController: UITableViewDataSource { } -fileprivate extension Data { +private extension Data { func hexString() -> String { let bytes = map { String(format: "%02hhx", $0) } diff --git a/DuckDuckGo/PrivacyProtectionOverviewController.swift b/DuckDuckGo/PrivacyProtectionOverviewController.swift index d50ba7a7d7..2d5f5717a9 100644 --- a/DuckDuckGo/PrivacyProtectionOverviewController.swift +++ b/DuckDuckGo/PrivacyProtectionOverviewController.swift @@ -341,7 +341,7 @@ class TrackerNetworkPillView: UIView { } -fileprivate extension PPTrackerNetwork { +private extension PPTrackerNetwork { var image: UIImage { let currentTrackerData = ContentBlocking.contentBlockingManager.currentTDSRules?.trackerData diff --git a/DuckDuckGo/PrivacyProtectionPracticesController.swift b/DuckDuckGo/PrivacyProtectionPracticesController.swift index d18a787245..8aec303ace 100644 --- a/DuckDuckGo/PrivacyProtectionPracticesController.swift +++ b/DuckDuckGo/PrivacyProtectionPracticesController.swift @@ -51,7 +51,8 @@ class PrivacyProtectionPracticesController: UIViewController { var rows = [Row]() override func viewDidLoad() { - + super.viewDidLoad() + Pixel.fire(pixel: .privacyDashboardPrivacyPractices) initTable() @@ -89,7 +90,7 @@ class PrivacyProtectionPracticesController: UIViewController { domainLabel.text = siteRating.domain } - private func updateReasons() { + private func updateReasons() { let goodReasons = siteRating.privacyPractice.goodReasons let badReasons = siteRating.privacyPractice.badReasons let goodRows = goodReasons.map({ Row(text: $0.capitalizingFirstLetter(), good: true) }) @@ -210,7 +211,7 @@ class PrivacyProtectionNoPracticesCell: UITableViewCell { } // Credit: https://stackoverflow.com/a/26306372/73479 -fileprivate extension String { +private extension String { func capitalizingFirstLetter() -> String { return prefix(1).uppercased() + dropFirst() } diff --git a/DuckDuckGo/PrivacyProtectionScoreCardController.swift b/DuckDuckGo/PrivacyProtectionScoreCardController.swift index 5be23de2c4..bbad9d685a 100644 --- a/DuckDuckGo/PrivacyProtectionScoreCardController.swift +++ b/DuckDuckGo/PrivacyProtectionScoreCardController.swift @@ -37,6 +37,8 @@ class PrivacyProtectionScoreCardController: UITableViewController { private var privacyConfig: PrivacyConfiguration = ContentBlocking.privacyConfigurationManager.privacyConfig override func viewDidLoad() { + super.viewDidLoad() + Pixel.fire(pixel: .privacyDashboardScorecard) tableView.register(UINib(nibName: "PrivacyProtectionHeaderCell", bundle: nil), diff --git a/DuckDuckGo/PrivacyProtectionTrackerNetworksController.swift b/DuckDuckGo/PrivacyProtectionTrackerNetworksController.swift index be6f55cfcd..08d8896498 100644 --- a/DuckDuckGo/PrivacyProtectionTrackerNetworksController.swift +++ b/DuckDuckGo/PrivacyProtectionTrackerNetworksController.swift @@ -57,7 +57,7 @@ class PrivacyProtectionTrackerNetworksController: UIViewController { var sections = [Section]() override func viewDidLoad() { - + super.viewDidLoad() Pixel.fire(pixel: .privacyDashboardNetworks) initTableView() diff --git a/DuckDuckGo/ProgressView.swift b/DuckDuckGo/ProgressView.swift index e37cd96db5..6bf41c25b3 100644 --- a/DuckDuckGo/ProgressView.swift +++ b/DuckDuckGo/ProgressView.swift @@ -197,6 +197,7 @@ class ProgressView: UIView, CAAnimationDelegate { // MARK: IB override func prepareForInterfaceBuilder() { + super.prepareForInterfaceBuilder() backgroundColor = .cornflowerBlue } } diff --git a/DuckDuckGo/RootDebugViewController.swift b/DuckDuckGo/RootDebugViewController.swift index 3a36c3e874..911e68f899 100644 --- a/DuckDuckGo/RootDebugViewController.swift +++ b/DuckDuckGo/RootDebugViewController.swift @@ -153,8 +153,8 @@ class DiagnosticReportDataSource: UIActivityItemProvider { } let processedCookies = cookies - .sorted(by: {$0.domain < $1.domain}) - .sorted(by: {$0.name < $1.name}) + .sorted(by: { $0.domain < $1.domain }) + .sorted(by: { $0.name < $1.name }) .map { $0.debugString } return (["## Cookie Report"] + timeout + processedCookies).joined(separator: "\n") @@ -169,7 +169,7 @@ class DiagnosticReportDataSource: UIActivityItemProvider { } -fileprivate extension ImageCache { +private extension ImageCache { var count: Int { let url = diskStorage.directoryURL @@ -183,7 +183,7 @@ fileprivate extension ImageCache { } -fileprivate extension HTTPCookie { +private extension HTTPCookie { var debugString: String { """ diff --git a/DuckDuckGo/SpeechRecognizer.swift b/DuckDuckGo/SpeechRecognizer.swift index 2c3eadad89..57c43c6853 100644 --- a/DuckDuckGo/SpeechRecognizer.swift +++ b/DuckDuckGo/SpeechRecognizer.swift @@ -88,7 +88,7 @@ final class SpeechRecognizer: NSObject, SpeechRecognizerProtocol { let silenceThreshold: Float = 0.0030 let loudThreshold: Float = 0.07 - let sumChannelData = channelDataArray.reduce(0) {$0 + abs($1)} + let sumChannelData = channelDataArray.reduce(0) { $0 + abs($1) } var channelAverage = sumChannelData / Float(channelDataArray.count) channelAverage = min(channelAverage, loudThreshold) channelAverage = max(channelAverage, silenceThreshold) diff --git a/DuckDuckGo/TabViewController.swift b/DuckDuckGo/TabViewController.swift index f0bfccde50..c0955d134c 100644 --- a/DuckDuckGo/TabViewController.swift +++ b/DuckDuckGo/TabViewController.swift @@ -845,7 +845,7 @@ class TabViewController: UIViewController { return BrokenSiteInfo(url: url, httpsUpgrade: httpsForced, blockedTrackerDomains: blockedTrackerDomains, - installedSurrogates: siteRating?.installedSurrogates.map {$0} ?? [], + installedSurrogates: siteRating?.installedSurrogates.map { $0 } ?? [], isDesktop: tabModel.isDesktop, tdsETag: ContentBlocking.contentBlockingManager.currentTDSRules?.etag ?? "", ampUrl: linkProtection.lastAMPURLString, diff --git a/DuckDuckGo/TabsBarCell.swift b/DuckDuckGo/TabsBarCell.swift index 950b8bdb23..54f5036659 100644 --- a/DuckDuckGo/TabsBarCell.swift +++ b/DuckDuckGo/TabsBarCell.swift @@ -106,7 +106,7 @@ class TabsBarCell: UICollectionViewCell { private func applyModel(_ model: Tab) { if model.link == nil { - faviconImage.loadFavicon(forDomain: Self.appUrls.base.host, usingCache: .tabs) + faviconImage.loadFavicon(forDomain: Self.appUrls.base.host, usingCache: .tabs) label.text = UserText.homeTabTitle label.accessibilityLabel = UserText.openHomeTab removeButton.accessibilityLabel = UserText.closeHomeTab diff --git a/DuckDuckGo/Theme.swift b/DuckDuckGo/Theme.swift index 2f968aeb3d..ff802a8cb3 100644 --- a/DuckDuckGo/Theme.swift +++ b/DuckDuckGo/Theme.swift @@ -33,7 +33,7 @@ protocol Theme { var keyboardAppearance: UIKeyboardAppearance { get } var tabsBarBackgroundColor: UIColor { get } - var tabsBarSeparatorColor: UIColor { get } + var tabsBarSeparatorColor: UIColor { get } var backgroundColor: UIColor { get } diff --git a/DuckDuckGo/WidgetEducationHomeMessage.swift b/DuckDuckGo/WidgetEducationHomeMessage.swift index b88245a758..41da7bad08 100644 --- a/DuckDuckGo/WidgetEducationHomeMessage.swift +++ b/DuckDuckGo/WidgetEducationHomeMessage.swift @@ -47,7 +47,7 @@ struct WidgetEducationHomeMessage { } private static func makeWidgetEducationViewController(presentingViewController: UIViewController) -> UIViewController { - guard #available(iOS 14.0, *) else { fatalError() } + guard #available(iOS 14.0, *) else { fatalError("Widget education should be available on iOS 15+ only") } return WidgetEducationViewController().embeddedInNavigationController } } diff --git a/DuckDuckGoTests/APIRequestTests.swift b/DuckDuckGoTests/APIRequestTests.swift index 0fa5e2ee6e..4cccd7472f 100644 --- a/DuckDuckGoTests/APIRequestTests.swift +++ b/DuckDuckGoTests/APIRequestTests.swift @@ -28,6 +28,8 @@ class APIRequestTests: XCTestCase { let url = AppUrls().surrogates override func setUp() { + super.setUp() + swizzlePreferredLanguagesMethod() } diff --git a/DuckDuckGoTests/AppConfigurationFetchTests.swift b/DuckDuckGoTests/AppConfigurationFetchTests.swift index d3324d517c..7a406285d5 100644 --- a/DuckDuckGoTests/AppConfigurationFetchTests.swift +++ b/DuckDuckGoTests/AppConfigurationFetchTests.swift @@ -26,6 +26,8 @@ class AppConfigurationFetchTests: XCTestCase { let testGroupName = "configurationFetchTestGroup" override func setUp() { + super.setUp() + UserDefaults(suiteName: testGroupName)?.removePersistentDomain(forName: testGroupName) } diff --git a/DuckDuckGoTests/AppHTTPSUpgradeStoreTests.swift b/DuckDuckGoTests/AppHTTPSUpgradeStoreTests.swift index 0dae5834dc..e8b5ea7882 100644 --- a/DuckDuckGoTests/AppHTTPSUpgradeStoreTests.swift +++ b/DuckDuckGoTests/AppHTTPSUpgradeStoreTests.swift @@ -26,11 +26,14 @@ final class AppHTTPSUpgradeStoreTests: XCTestCase { var testee: AppHTTPSUpgradeStore! override func setUp() { + super.setUp() testee = AppHTTPSUpgradeStore() testee.reset() } override func tearDown() { + super.tearDown() + testee.reset() } diff --git a/DuckDuckGoTests/AppRatingPromptTests.swift b/DuckDuckGoTests/AppRatingPromptTests.swift index 4fb224bb87..582a2ba310 100644 --- a/DuckDuckGoTests/AppRatingPromptTests.swift +++ b/DuckDuckGoTests/AppRatingPromptTests.swift @@ -130,7 +130,7 @@ private class AppRatingPromptStorageStub: AppRatingPromptStorage { } -fileprivate extension Date { +private extension Date { func inDays(fromNow day: Int) -> Date { let components = DateComponents(day: day) diff --git a/DuckDuckGoTests/AppUserDefaultsTests.swift b/DuckDuckGoTests/AppUserDefaultsTests.swift index d8a0e0365f..10fd1f7347 100644 --- a/DuckDuckGoTests/AppUserDefaultsTests.swift +++ b/DuckDuckGoTests/AppUserDefaultsTests.swift @@ -25,6 +25,7 @@ class AppUserDefaultsTests: XCTestCase { let testGroupName = "test" override func setUp() { + super.setUp() UserDefaults(suiteName: testGroupName)?.removePersistentDomain(forName: testGroupName) } diff --git a/DuckDuckGoTests/AppVersionExtensionTests.swift b/DuckDuckGoTests/AppVersionExtensionTests.swift index 33c2d3084f..7902fe0e28 100644 --- a/DuckDuckGoTests/AppVersionExtensionTests.swift +++ b/DuckDuckGoTests/AppVersionExtensionTests.swift @@ -33,6 +33,8 @@ class AppVersionExtensionTests: XCTestCase { private var testee: AppVersion! override func setUp() { + super.setUp() + mockBundle = MockBundle() testee = AppVersion(bundle: mockBundle) } diff --git a/DuckDuckGoTests/AppVersionTests.swift b/DuckDuckGoTests/AppVersionTests.swift index 1a441e7a8d..38ee9bfd52 100644 --- a/DuckDuckGoTests/AppVersionTests.swift +++ b/DuckDuckGoTests/AppVersionTests.swift @@ -33,6 +33,8 @@ class AppVersionTests: XCTestCase { private var testee: AppVersion! override func setUp() { + super.setUp() + mockBundle = MockBundle() testee = AppVersion(bundle: mockBundle) } diff --git a/DuckDuckGoTests/AutoClearSettingsScreenTests.swift b/DuckDuckGoTests/AutoClearSettingsScreenTests.swift index 7fad90b1e5..e4ce725474 100644 --- a/DuckDuckGoTests/AutoClearSettingsScreenTests.swift +++ b/DuckDuckGoTests/AutoClearSettingsScreenTests.swift @@ -26,11 +26,15 @@ class AutoClearSettingsScreenTests: XCTestCase { var mockDependencyProvider: MockDependencyProvider! override func setUp() { + super.setUp() + mockDependencyProvider = MockDependencyProvider() AppDependencyProvider.shared = mockDependencyProvider } override func tearDown() { + super.tearDown() + AppDependencyProvider.shared = AppDependencyProvider() } @@ -79,7 +83,7 @@ class AutoClearSettingsScreenTests: XCTestCase { } } -fileprivate extension AutoClearSettingsViewController { +private extension AutoClearSettingsViewController { static func loadFromStoryboard() -> AutoClearSettingsViewController? { let controller = UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "AutoClearSettingsViewController") diff --git a/DuckDuckGoTests/AutoClearTests.swift b/DuckDuckGoTests/AutoClearTests.swift index 4eec2179c3..71a2a4dd1c 100644 --- a/DuckDuckGoTests/AutoClearTests.swift +++ b/DuckDuckGoTests/AutoClearTests.swift @@ -46,6 +46,8 @@ class AutoClearTests: XCTestCase { private var logic: AutoClear! override func setUp() { + super.setUp() + worker = MockWorker() logic = AutoClear(worker: worker) } diff --git a/DuckDuckGoTests/BookmarksCachingSearchTests.swift b/DuckDuckGoTests/BookmarksCachingSearchTests.swift index 0b6017db95..7c473035c8 100644 --- a/DuckDuckGoTests/BookmarksCachingSearchTests.swift +++ b/DuckDuckGoTests/BookmarksCachingSearchTests.swift @@ -49,7 +49,7 @@ class MockBookmark: Bookmark { } var objectID: NSManagedObjectID { - fatalError() + fatalError("objectID should exist") } var parentFolder: BookmarkFolder? @@ -79,6 +79,8 @@ class BookmarksCachingSearchTests: XCTestCase { } override func setUp() { + super.setUp() + simpleStore.bookmarks = [MockBookmark(title: Entry.b1.rawValue, url: url, isFavorite: false), MockBookmark(title: Entry.b2.rawValue, url: url, isFavorite: false), MockBookmark(title: Entry.b12.rawValue, url: url, isFavorite: false), @@ -310,6 +312,6 @@ class BookmarksCachingSearchTests: XCTestCase { expectation4.fulfill() } - waitForExpectations(timeout: 5) + waitForExpectations(timeout: 5) } } diff --git a/DuckDuckGoTests/DatabaseMigrationTests.swift b/DuckDuckGoTests/DatabaseMigrationTests.swift index cff54b1be0..f979a1cf49 100644 --- a/DuckDuckGoTests/DatabaseMigrationTests.swift +++ b/DuckDuckGoTests/DatabaseMigrationTests.swift @@ -27,6 +27,8 @@ class DatabaseMigrationTests: XCTestCase { let sourceDB = Database(name: "Source", model: Database.shared.model) override func setUp() { + super.setUp() + sourceDB.loadStore() cleanup(database: Database.shared) @@ -34,6 +36,8 @@ class DatabaseMigrationTests: XCTestCase { } override func tearDown() { + super.tearDown() + cleanup(database: Database.shared) cleanup(database: sourceDB) } @@ -118,7 +122,7 @@ class DatabaseMigrationTests: XCTestCase { result = (try? destination.fetch(PPTrackerNetwork.fetchRequest())) ?? [] XCTAssert(result.count == 2) XCTAssert(destination.hasChanges) - let modified = destination.updatedObjects.first(where: { ($0 as? PPTrackerNetwork)?.name == "Updated"}) + let modified = destination.updatedObjects.first(where: { ($0 as? PPTrackerNetwork)?.name == "Updated" }) XCTAssertNotNil(modified) result = (try? source.fetch(PPTrackerNetwork.fetchRequest())) ?? [] diff --git a/DuckDuckGoTests/DaxDialogsBrowsingSpecTests.swift b/DuckDuckGoTests/DaxDialogsBrowsingSpecTests.swift index 35461131ee..4312a60639 100644 --- a/DuckDuckGoTests/DaxDialogsBrowsingSpecTests.swift +++ b/DuckDuckGoTests/DaxDialogsBrowsingSpecTests.swift @@ -88,7 +88,7 @@ class DaxDialogsBrowsingSpecTests: XCTestCase { } // From: https://stackoverflow.com/a/49547114/73479 -fileprivate extension String { +private extension String { func countInstances(of stringToFind: String) -> Int { var stringToSearch = self var count = 0 diff --git a/DuckDuckGoTests/DomainsProtectionUserDefaultsStoreTests.swift b/DuckDuckGoTests/DomainsProtectionUserDefaultsStoreTests.swift index 3af3b35422..0e7a86dca5 100644 --- a/DuckDuckGoTests/DomainsProtectionUserDefaultsStoreTests.swift +++ b/DuckDuckGoTests/DomainsProtectionUserDefaultsStoreTests.swift @@ -31,6 +31,8 @@ class DomainsProtectionUserDefaultsStoreTests: XCTestCase { var testee: DomainsProtectionUserDefaultsStore! override func setUp() { + super.setUp() + UserDefaults().removePersistentDomain(forName: Constants.userDefaultsSuit) testee = DomainsProtectionUserDefaultsStore(suiteName: Constants.userDefaultsSuit) } diff --git a/DuckDuckGoTests/DownloadManagerTests.swift b/DuckDuckGoTests/DownloadManagerTests.swift index 26d940f76d..b4d428d268 100644 --- a/DuckDuckGoTests/DownloadManagerTests.swift +++ b/DuckDuckGoTests/DownloadManagerTests.swift @@ -28,10 +28,8 @@ class DownloadManagerTests: XCTestCase { var mockDependencyProvider: MockDependencyProvider! - override func setUp() { - } - override func tearDown() { + super.tearDown() downloadManagerTestsHelper.deleteAllFiles() } diff --git a/DuckDuckGoTests/DownloadTests.swift b/DuckDuckGoTests/DownloadTests.swift index cf04f0f831..0f885f8ae5 100644 --- a/DuckDuckGoTests/DownloadTests.swift +++ b/DuckDuckGoTests/DownloadTests.swift @@ -23,10 +23,8 @@ import XCTest class DownloadTests: XCTestCase { private let downloadManagerTestsHelper = DownloadTestsHelper(downloadsDirectory: DownloadManager().downloadsDirectory) - override func setUpWithError() throws { - } - override func tearDownWithError() throws { + try super.tearDownWithError() downloadManagerTestsHelper.deleteAllFiles() } diff --git a/DuckDuckGoTests/HomeRowReminderTests.swift b/DuckDuckGoTests/HomeRowReminderTests.swift index 8408a14df3..c0e44358f5 100644 --- a/DuckDuckGoTests/HomeRowReminderTests.swift +++ b/DuckDuckGoTests/HomeRowReminderTests.swift @@ -26,6 +26,8 @@ class HomeRowReminderTests: XCTestCase { var storage: MockHomeRowReminderStorage! override func setUp() { + super.setUp() + storage = MockHomeRowReminderStorage() } diff --git a/DuckDuckGoTests/InitHelpers.swift b/DuckDuckGoTests/InitHelpers.swift index 4e7ac89953..8607dd5a41 100644 --- a/DuckDuckGoTests/InitHelpers.swift +++ b/DuckDuckGoTests/InitHelpers.swift @@ -87,7 +87,6 @@ extension HTTPCookie { properties[HTTPCookiePropertyKey.sameSitePolicy] = policy } - return HTTPCookie(properties: properties)! - } + return HTTPCookie(properties: properties)! } } diff --git a/DuckDuckGoTests/LargeOmniBarStateTests.swift b/DuckDuckGoTests/LargeOmniBarStateTests.swift index 7d2d82113c..195931b365 100644 --- a/DuckDuckGoTests/LargeOmniBarStateTests.swift +++ b/DuckDuckGoTests/LargeOmniBarStateTests.swift @@ -30,11 +30,15 @@ class LargeOmniBarStateTests: XCTestCase { var mockDependencyProvider: MockDependencyProvider! override func setUp() { + super.setUp() + mockDependencyProvider = MockDependencyProvider() AppDependencyProvider.shared = mockDependencyProvider } override func tearDown() { + super.tearDown() + AppDependencyProvider.shared = AppDependencyProvider() } diff --git a/DuckDuckGoTests/NetworkLeaderboardTests.swift b/DuckDuckGoTests/NetworkLeaderboardTests.swift index f1e12fd34a..0e769e34ab 100644 --- a/DuckDuckGoTests/NetworkLeaderboardTests.swift +++ b/DuckDuckGoTests/NetworkLeaderboardTests.swift @@ -24,6 +24,8 @@ import XCTest class NetworkLeaderboardTests: XCTestCase { override func setUp() { + super.setUp() + NetworkLeaderboard().reset() UserDefaults(suiteName: "test")?.removePersistentDomain(forName: "test") } diff --git a/DuckDuckGoTests/PreserveLoginsTests.swift b/DuckDuckGoTests/PreserveLoginsTests.swift index c85b875324..aa02ec3bb9 100644 --- a/DuckDuckGoTests/PreserveLoginsTests.swift +++ b/DuckDuckGoTests/PreserveLoginsTests.swift @@ -23,6 +23,8 @@ import XCTest class PreserveLoginsTests: XCTestCase { override func setUp() { + super.setUp() + UserDefaultsWrapper.clearAll() } diff --git a/DuckDuckGoTests/SettingsViewControllerTests.swift b/DuckDuckGoTests/SettingsViewControllerTests.swift index 6fed52f6eb..9fdc896368 100644 --- a/DuckDuckGoTests/SettingsViewControllerTests.swift +++ b/DuckDuckGoTests/SettingsViewControllerTests.swift @@ -25,11 +25,14 @@ class SettingsViewControllerTests: XCTestCase { var mockDependencyProvider: MockDependencyProvider! override func setUp() { + super.setUp() + mockDependencyProvider = MockDependencyProvider() AppDependencyProvider.shared = mockDependencyProvider } override func tearDown() { + super.tearDown() AppDependencyProvider.shared = AppDependencyProvider() } diff --git a/DuckDuckGoTests/SiteRatingTests.swift b/DuckDuckGoTests/SiteRatingTests.swift index ef1ce9a033..14ba85b238 100644 --- a/DuckDuckGoTests/SiteRatingTests.swift +++ b/DuckDuckGoTests/SiteRatingTests.swift @@ -67,6 +67,8 @@ class SiteRatingTests: XCTestCase { fileprivate let classATOS = MockTermsOfServiceStore().add(domain: "example.com", classification: .a, score: -100) override func setUp() { + super.setUp() + GradeCache.shared.reset() } @@ -246,7 +248,7 @@ private class MockTermsOfServiceStore: TermsOfServiceStore { } -fileprivate extension KnownTracker { +private extension KnownTracker { static func build(domain: String, ownerName: String, category: String) -> KnownTracker { let owner = KnownTracker.Owner(name: ownerName, displayName: ownerName) diff --git a/DuckDuckGoTests/SmallOmniBarStateTests.swift b/DuckDuckGoTests/SmallOmniBarStateTests.swift index 559700ac20..ffa82d3011 100644 --- a/DuckDuckGoTests/SmallOmniBarStateTests.swift +++ b/DuckDuckGoTests/SmallOmniBarStateTests.swift @@ -30,11 +30,15 @@ class SmallOmniBarStateTests: XCTestCase { var mockDependencyProvider: MockDependencyProvider! override func setUp() { + super.setUp() + mockDependencyProvider = MockDependencyProvider() AppDependencyProvider.shared = mockDependencyProvider } override func tearDown() { + super.tearDown() + AppDependencyProvider.shared = AppDependencyProvider() } diff --git a/DuckDuckGoTests/StatisticsLoaderTests.swift b/DuckDuckGoTests/StatisticsLoaderTests.swift index 3f25cc5bc8..dd77a6fdfb 100644 --- a/DuckDuckGoTests/StatisticsLoaderTests.swift +++ b/DuckDuckGoTests/StatisticsLoaderTests.swift @@ -29,6 +29,8 @@ class StatisticsLoaderTests: XCTestCase { var testee: StatisticsLoader! override func setUp() { + super.setUp() + mockStatisticsStore = MockStatisticsStore() testee = StatisticsLoader(statisticsStore: mockStatisticsStore) } diff --git a/DuckDuckGoTests/StatisticsUserDefaultsTests.swift b/DuckDuckGoTests/StatisticsUserDefaultsTests.swift index f02dc741c9..3ac932223a 100644 --- a/DuckDuckGoTests/StatisticsUserDefaultsTests.swift +++ b/DuckDuckGoTests/StatisticsUserDefaultsTests.swift @@ -33,6 +33,8 @@ class StatisticsUserDefaultsTests: XCTestCase { var testee: StatisticsUserDefaults! override func setUp() { + super.setUp() + UserDefaults().removePersistentDomain(forName: Constants.userDefaultsSuit) testee = StatisticsUserDefaults(groupName: Constants.userDefaultsSuit) } diff --git a/DuckDuckGoTests/TabPreviewsSourceTests.swift b/DuckDuckGoTests/TabPreviewsSourceTests.swift index 3c488ad10b..99f0063d22 100644 --- a/DuckDuckGoTests/TabPreviewsSourceTests.swift +++ b/DuckDuckGoTests/TabPreviewsSourceTests.swift @@ -31,6 +31,8 @@ class TabPreviewsSourceTests: XCTestCase { private let containerUrl = TabPreviewsSourceTests.makeContainerUrl() override func setUp() { + super.setUp() + guard let containerUrl = containerUrl else { XCTFail("Could not determine containerUrl") return @@ -46,6 +48,8 @@ class TabPreviewsSourceTests: XCTestCase { } override func tearDown() { + super.tearDown() + guard let containerUrl = containerUrl else { XCTFail("Could not determine containerUrl") return diff --git a/DuckDuckGoTests/TabsModelPersistenceExtensionTests.swift b/DuckDuckGoTests/TabsModelPersistenceExtensionTests.swift index 143b869de1..e8b058ceb2 100644 --- a/DuckDuckGoTests/TabsModelPersistenceExtensionTests.swift +++ b/DuckDuckGoTests/TabsModelPersistenceExtensionTests.swift @@ -31,6 +31,8 @@ class TabsModelPersistenceExtensionTests: XCTestCase { } override func setUp() { + super.setUp() + UserDefaults.standard.removeObject(forKey: "com.duckduckgo.opentabs") } diff --git a/DuckDuckGoTests/UserDefaultsHomeRowReminderStorageTests.swift b/DuckDuckGoTests/UserDefaultsHomeRowReminderStorageTests.swift index cd60937953..0274dc946c 100644 --- a/DuckDuckGoTests/UserDefaultsHomeRowReminderStorageTests.swift +++ b/DuckDuckGoTests/UserDefaultsHomeRowReminderStorageTests.swift @@ -26,6 +26,8 @@ class UserDefaultsHomeRowReminderStorageTests: XCTestCase { let defaultsName = "UserDefaultsHomeRowReminderStorageTests" override func setUp() { + super.setUp() + UserDefaults(suiteName: defaultsName)?.removePersistentDomain(forName: defaultsName) } diff --git a/DuckDuckGoTests/VariantManagerTests.swift b/DuckDuckGoTests/VariantManagerTests.swift index e54c281c5a..1ff43719cb 100644 --- a/DuckDuckGoTests/VariantManagerTests.swift +++ b/DuckDuckGoTests/VariantManagerTests.swift @@ -62,7 +62,7 @@ class VariantManagerTests: XCTestCase { for i in 0 ..< 100 { let subject = DefaultVariantManager(variants: testVariants, storage: mockStore, rng: MockVariantRNG(returnValue: i)) - subject.assignVariantIfNeeded { _ in } + subject.assignVariantIfNeeded { _ in } XCTAssertNotEqual("mt", subject.currentVariant?.name) } @@ -75,7 +75,7 @@ class VariantManagerTests: XCTestCase { mockStore.atb = "atb" let subject = DefaultVariantManager(variants: testVariants, storage: mockStore, rng: MockVariantRNG(returnValue: 0)) - subject.assignVariantIfNeeded { _ in } + subject.assignVariantIfNeeded { _ in } XCTAssertNil(subject.currentVariant) } @@ -84,7 +84,7 @@ class VariantManagerTests: XCTestCase { let variant = Variant(name: "anything", weight: 100, isIncluded: Variant.When.always, features: []) let subject = DefaultVariantManager(variants: [variant], storage: MockStatisticsStore()) - subject.assignVariantIfNeeded { _ in } + subject.assignVariantIfNeeded { _ in } XCTAssertEqual(variant.name, subject.currentVariant?.name) } diff --git a/FingerprintingUITests/FingerprintUITest.swift b/FingerprintingUITests/FingerprintUITest.swift index 5b8b6d5441..6c01aef723 100644 --- a/FingerprintingUITests/FingerprintUITest.swift +++ b/FingerprintingUITests/FingerprintUITest.swift @@ -24,6 +24,8 @@ import XCTest class FingerprintUITest: XCTestCase { override func setUpWithError() throws { + try super.setUpWithError() + continueAfterFailure = false let app = XCUIApplication() @@ -65,6 +67,7 @@ class FingerprintUITest: XCTestCase { } override func tearDownWithError() throws { + try super.tearDownWithError() removeTheBookmark() } diff --git a/Widgets/Widgets.swift b/Widgets/Widgets.swift index a890f22106..c4db24d735 100644 --- a/Widgets/Widgets.swift +++ b/Widgets/Widgets.swift @@ -62,17 +62,17 @@ struct Provider: TimelineProvider { completion(timeline) } } - + private func coreDataFavoritesToFavories(_ coreDataFavorites: [Bookmark], returningNoMoreThan maxLength: Int) -> [Favorite] { return coreDataFavorites.prefix(maxLength) .compactMap { - guard let url = $0.url else { return nil } - return Favorite(url: DeepLinks.createFavoriteLauncher(forUrl: url), - domain: url.host?.dropPrefix(prefix: "www.") ?? "", - title: $0.displayTitle ?? "", - favicon: loadImageFromCache(forDomain: url.host) ) - } + guard let url = $0.url else { return nil } + return Favorite(url: DeepLinks.createFavoriteLauncher(forUrl: url), + domain: url.host?.dropPrefix(prefix: "www.") ?? "", + title: $0.displayTitle ?? "", + favicon: loadImageFromCache(forDomain: url.host) ) + } } private func getCoreDataFavorites(completion: @escaping ([Bookmark]) -> Void) { diff --git a/styleguide/STYLEGUIDE.md b/styleguide/STYLEGUIDE.md index 6c9fa35f6d..854d07b5c3 100644 --- a/styleguide/STYLEGUIDE.md +++ b/styleguide/STYLEGUIDE.md @@ -1,50 +1,1079 @@ -## General +This style guide was originally forked from [The official raywenderlich.com Swift Style Guide](https://github.com/raywenderlich/swift-style-guide) +## Table of Contents -* We care about clean code and aim to make this codebase as self-documenting and readable as possible. -* We primarily use Swift and the conventions enforced by Swift Lint except for the tweaks listed in [.swiftlint.yml](../.swiftlint.yml), which are described below. To see the rules and how they apply to this project, from the project root directory execute `swiftlint rules`. -* There may be instances of code that pre-dates our use of this style guide, these can be refactored as we encounter them. +* [Correctness](#correctness) +* [Using SwiftLint](#using-swiftlint) +* [Naming](#naming) + * [Prose](#prose) + * [Delegates](#delegates) + * [Use Type Inferred Context](#use-type-inferred-context) + * [Generics](#generics) + * [Class Prefixes](#class-prefixes) + * [Language](#language) +* [Code Organization](#code-organization) + * [Protocol Conformance](#protocol-conformance) + * [Unused Code](#unused-code) + * [Minimal Imports](#minimal-imports) +* [Line Breaks](#line-breaks) +* [Spacing](#spacing) +* [Comments](#comments) +* [Class Definition](#class-definition) + * [Use of Self](#use-of-self) + * [Protocol Conformance](#protocol-conformance) + * [Computed Properties](#computed-properties) + * [Final](#final) +* [Function Declarations](#function-declarations) +* [Function Calls](#function-calls) +* [Closure Expressions](#closure-expressions) +* [Types](#types) + * [Constants](#constants) + * [Static Methods and Variable Type Properties](#static-methods-and-variable-type-properties) + * [Optionals](#optionals) + * [Lazy Initialization](#lazy-initialization) + * [Type Inference](#type-inference) + * [Syntactic Sugar](#syntactic-sugar) +* [Functions vs Methods](#functions-vs-methods) +* [Memory Management](#memory-management) + * [Extending Object Lifetime](#extending-object-lifetime) +* [Access Control](#access-control) +* [Control Flow](#control-flow) + * [Ternary Operator](#ternary-operator) +* [Golden Path](#golden-path) + * [Failing Guards](#failing-guards) +* [Semicolons](#semicolons) +* [Parentheses](#parentheses) +* [Multi-line String Literals](#multi-line-string-literals) +* [No Emoji](#no-emoji) +* [No #imageLiteral or #colorLiteral](#no-imageliteral-or-colorliteral) +* [Assertions and Fatal Errors](#assertions-and-fatal-errors) +* [Logging](#logging) +* [Unit Test Names](#unit-test-names) -**IDE Setup:** +## Correctness -You must install Swift Lint. You can do this using `brew install swiftlint` or install it manually. Xcode will then generate warnings and errors for style violations. +Strive to make your code compile without warnings. This rule informs many style decisions such as using `#selector` types instead of string literals. -### Line breaks +## Using SwiftLint + +When writing for raywenderlich.com, you are strongly encouraged — and some teams may require — to use our SwiftLint configuration. See the [SwiftLint Policy](SWIFTLINT.markdown) for more information. + +## Naming + +Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in the [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). Some key takeaways include: + +- striving for clarity at the call site +- prioritizing clarity over brevity +- using `camelCase` (not `snake_case`) +- using `UpperCamelCase` for types and protocols, `lowerCamelCase` for everything else +- including all needed words while omitting needless words +- using names based on roles, not types +- sometimes compensating for weak type information +- striving for fluent usage +- beginning factory methods with `make` +- naming methods for their side effects + - verb methods follow the -ed, -ing rule for the non-mutating version + - noun methods follow the formX rule for the mutating version + - boolean types should read like assertions + - protocols that describe _what something is_ should read as nouns + - protocols that describe _a capability_ should end in _-able_ or _-ible_ +- using terms that don't surprise experts or confuse beginners +- generally avoiding abbreviations +- using precedent for names +- preferring methods and properties to free functions +- casing acronyms and initialisms uniformly up or down +- giving the same base name to methods that share the same meaning +- avoiding overloads on return type +- choosing good parameter names that serve as documentation +- preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates +- labeling closure and tuple parameters +- taking advantage of default parameters + +### Prose + +When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible. + +1. Write the method name with no parameters. **Example:** Next, you need to call `addTarget`. +2. Write the method name with argument labels. **Example:** Next, you need to call `addTarget(_:action:)`. +3. Write the full method name with argument labels and types. **Example:** Next, you need to call `addTarget(_: Any?, action: Selector?)`. + +For the above example using `UIGestureRecognizer`, 1 is unambiguous and preferred. + +**Pro Tip:** You can use Xcode's jump bar to lookup methods with argument labels. If you’re particularly good at mashing lots of keys simultaneously, put the cursor in the method name and press **Shift-Control-Option-Command-C** (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard. + +![Methods in Xcode jump bar](screens/xcode-jump-bar.png) + + +### Class Prefixes + +Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as RW. If two names from different modules collide you can disambiguate by prefixing the type name with the module name. However, only specify the module name when there is possibility for confusion, which should be rare. + +```swift +import SomeModule + +let myClass = MyModule.UsefulClass() +``` + +### Delegates + +When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.) + +**Preferred**: +```swift +func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String) +func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool +``` + +**Not Preferred**: +```swift +func didSelectName(namePicker: NamePickerViewController, name: String) +func namePickerShouldReload() -> Bool +``` + +### Use Type Inferred Context + +Use compiler inferred context to write shorter, clear code. (Also see [Type Inference](#type-inference).) + +**Preferred**: +```swift +let selector = #selector(viewDidLoad) +view.backgroundColor = .red +let toView = context.view(forKey: .to) +let view = UIView(frame: .zero) +``` + +**Not Preferred**: +```swift +let selector = #selector(ViewController.viewDidLoad) +view.backgroundColor = UIColor.red +let toView = context.view(forKey: UITransitionContextViewKey.to) +let view = UIView(frame: CGRect.zero) +``` + +### Generics + +Generic type parameters should be descriptive, upper camel case names. When a type name doesn't have a meaningful relationship or role, use a traditional single uppercase letter such as `T`, `U`, or `V`. + +**Preferred**: +```swift +struct Stack { ... } +func write(to target: inout Target) +func swap(_ a: inout T, _ b: inout T) +``` + +**Not Preferred**: +```swift +struct Stack { ... } +func write(to target: inout target) +func swap(_ a: inout Thing, _ b: inout Thing) +``` + +### Language + +Use US English spelling to match Apple's API. + +**Preferred**: +```swift +let color = "red" +``` + +**Not Preferred**: +```swift +let colour = "red" +``` + +## Code Organization + +Use extensions to organize your code into logical blocks of functionality. Each extension should be set off with a `// MARK: -` comment to keep things well-organized. + +### Protocol Conformance + +In particular, when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods. + +**Preferred**: +```swift +class MyViewController: UIViewController { + // class stuff here +} + +// MARK: - UITableViewDataSource +extension MyViewController: UITableViewDataSource { + // table view data source methods +} + +// MARK: - UIScrollViewDelegate +extension MyViewController: UIScrollViewDelegate { + // scroll view delegate methods +} +``` + +**Not Preferred**: +```swift +class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate { + // all methods +} +``` + +Since the compiler does not allow you to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class. This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the author. + +For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions. + +### Unused Code + +Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when your tutorial or book instructs the user to use the commented code. + +Aspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods. + +**Preferred**: +```swift +override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return Database.contacts.count +} +``` + +**Not Preferred**: +```swift +override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. +} + +override func numberOfSections(in tableView: UITableView) -> Int { + // #warning Incomplete implementation, return the number of sections + return 1 +} + +override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + // #warning Incomplete implementation, return the number of rows + return Database.contacts.count +} + +``` +### Minimal Imports + +Import only the modules a source file requires. For example, don't import `UIKit` when importing `Foundation` will suffice. Likewise, don't import `Foundation` if you must import `UIKit`. + +**Preferred**: +```swift +import UIKit +var view: UIView +var deviceModels: [String] +``` + +**Preferred**: +```swift +import Foundation +var deviceModels: [String] +``` + +**Not Preferred**: +```swift +import UIKit +import Foundation +var view: UIView +var deviceModels: [String] +``` + +**Not Preferred**: +```swift +import UIKit +var deviceModels: [String] +``` + +## Line Breaks We use a line margin of 150 rather than the default of 100 as the default causes excessive line breaks. The larger margin allows us to take advantage of modern widescreen monitors with more screen real-estate. -**IDE Setup:** +## Spacing -Xcode won't enforce or autoformat for you, but you can set up a page column at 150 characters. +* Indent using 4 spaces rather than tabs Be sure to set this preference in Xcode -![Setting page guide column](xcode-page-guide.png) +* Method braces and other braces (`if`/`else`/`switch`/`while` etc.) always open on the same line as the statement but close on a new line. +* Tip: You can re-indent by selecting some code (or **Command-A** to select all) and then **Control-I** (or **Editor ▸ Structure ▸ Re-Indent** in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that. -Also check `Including whitespace-only lines` under `Preferences > Text Editing > Editing > Automatically trim trailing whitespace`. +**Preferred**: +```swift +if user.isHappy { + // Do something +} else { + // Do something else +} +``` -### Identifier names +**Not Preferred**: +```swift +if user.isHappy +{ + // Do something +} +else { + // Do something else +} +``` -Identifier names (e.g. variables, enum values, etc) must have a minimum length of 1 characters and a maximum length of 60 characters. +* There should be one blank line between methods and up to one blank line between type declarations to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods. -### Type names +* There should be no blank lines after an opening brace or before a closing brace. -Type names (e.g. classes, structs, etc) must have a minimum length of 3 characters and a maximum length of 100 characters. +* Closing parentheses should not appear on a line by themselves. -### Multiline function parameters +**Preferred**: +```swift +let user = try await getUser( + for: userID, + on: connection) +``` -If you separate a function definition or call on to separate lines (because of the line length rule, perhaps) then _each_ parameter should be on a separate line. Xcode should automatically align them for you. +**Not Preferred**: +```swift +let user = try await getUser( + for: userID, + on: connection +) +``` -This won't be enforced by Swift Lint. +* Colons always have no space on the left and one space on the right. Exceptions are the ternary operator `? :`, empty dictionary `[:]` and `#selector` syntax `addTarget(_:action:)`. -### Logging +**Preferred**: +```swift +class TestDatabase: Database { + var data: [String: CGFloat] = ["A": 1.2, "B": 3.2] +} +``` -We use [unified logging system](https://developer.apple.com/documentation/os/logging) to capture log messages. To send a message to the logging system, call the `os_log` function. Please use debug log level to protect users' privacy. +**Not Preferred**: +```swift +class TestDatabase : Database { + var data :[String:CGFloat] = ["A" : 1.2, "B":3.2] +} +``` + +* Long lines should be wrapped at around 150 characters. A hard limit is intentionally not specified. + +* Avoid trailing whitespaces at the ends of lines. + +* Add a single newline character at the end of each file. + +## Comments + +When they are needed, use comments to explain **why** a particular piece of code does something. Comments must be kept up-to-date or deleted. + +Avoid block comments inline with code, as the code should be as self-documenting as possible. _Exception: This does not apply to those comments used to generate documentation._ + +Avoid the use of C-style comments (`/* ... */`). Prefer the use of double- or triple-slash. + + +## Class Definition + +Here's an example of a well-styled class definition: + +```swift +final class Circle: Shape { + var x: Int, y: Int + var radius: Double + var diameter: Double { + get { + radius * 2 + } + set { + radius = newValue / 2 + } + } + + init(x: Int, y: Int, radius: Double) { + self.x = x + self.y = y + self.radius = radius + } + + convenience init(x: Int, y: Int, diameter: Double) { + self.init(x: x, y: y, radius: diameter / 2) + } + + override func area() -> Double { + Double.pi * radius * radius + } +} + +extension Circle: CustomStringConvertible { + var description: String { + "center = \(centerString) area = \(area())" + } + private var centerString: String { + "(\(x),\(y))" + } +} +``` + +The example above demonstrates the following style guidelines: + + + Specify types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g. `x: Int`, and `Circle: Shape`. + + Define multiple variables and structures on a single line if they share a common purpose / context. + + Indent getter and setter definitions and property observers. + + Don't add modifiers such as `internal` when they're already the default. Similarly, don't repeat the access modifier when overriding a method. + + Organize extra functionality (e.g. printing) in extensions. + + Hide non-shared, implementation details such as `centerString` inside the extension using `private` access control. + +### Use of Self + +For conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods. + +Use self only when required by the compiler (in `@escaping` closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without `self` then omit it. + + +### Computed Properties + +For conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided. + +**Preferred**: +```swift +var diameter: Double { + radius * 2 +} +``` + +**Not Preferred**: +```swift +var diameter: Double { + get { + return radius * 2 + } +} +``` + +### Final + +Marking classes or members as `final` in tutorials can distract from the main topic and is not required. Nevertheless, use of `final` can sometimes clarify your intent and is worth the cost. In the below example, `Box` has a particular purpose and customization in a derived class is not intended. Marking it `final` makes that clear. + +```swift +// Turn any generic type into a reference type using this Box class. +final class Box { + let value: T + init(_ value: T) { + self.value = value + } +} +``` + +## Function Declarations + +Keep short function declarations on one line including the opening brace: + +```swift +func reticulateSplines(spline: [Double]) -> Bool { + // reticulate code goes here +} +``` + +For functions with long signatures, put each following parameter on a new line: + +```swift +func reticulateSplines(spline: [Double], + adjustmentFactor: Double, + translateConstant: Int, + comment: String) -> Bool { + // reticulate code goes here +} +``` + +Don't use `(Void)` to represent the lack of an input; simply use `()`. Use `Void` instead of `()` for closure and function outputs. + +**Preferred**: + +```swift +func updateConstraints() -> Void { + // magic happens here +} + +typealias CompletionHandler = (result) -> Void +``` + +**Not Preferred**: + +```swift +func updateConstraints() -> () { + // magic happens here +} + +typealias CompletionHandler = (result) -> () +``` + +## Function Calls + +Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such: + +```swift +let success = reticulateSplines(splines) +``` + +If the call site must be wrapped, put each parameter on a new line, indented one additional level: + +```swift +let success = reticulateSplines( + spline: splines, + adjustmentFactor: 1.3, + translateConstant: 2, + comment: "normalize the display") +``` + +## Closure Expressions + +Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names. + +**Preferred**: +```swift +UIView.animate(withDuration: 1.0) { + self.myView.alpha = 0 +} + +UIView.animate(withDuration: 1.0, animations: { + self.myView.alpha = 0 +}, completion: { finished in + self.myView.removeFromSuperview() +}) +``` + +**Not Preferred**: +```swift +UIView.animate(withDuration: 1.0, animations: { + self.myView.alpha = 0 +}) + +UIView.animate(withDuration: 1.0, animations: { + self.myView.alpha = 0 +}) { f in + self.myView.removeFromSuperview() +} +``` + +For single-expression closures where the context is clear, use implicit returns: + +```swift +attendeeList.sort { a, b in + a > b +} +``` + +Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the author. Examples: + +```swift +let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90) + +let value = numbers + .map {$0 * 2} + .filter {$0 > 50} + .map {$0 + 10} +``` + +## Types + +Always use Swift's native types and expressions when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed. + +**Preferred**: +```swift +let width = 120.0 // Double +let widthString = "\(width)" // String +``` + +**Less Preferred**: +```swift +let width = 120.0 // Double +let widthString = (width as NSNumber).stringValue // String +``` + +**Not Preferred**: +```swift +let width: NSNumber = 120.0 // NSNumber +let widthString: NSString = width.stringValue // NSString +``` + +In drawing code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions. + +### Constants + +Constants are defined using the `let` keyword and variables with the `var` keyword. Always use `let` instead of `var` if the value of the variable will not change. -### Assertions and fatal errors +**Tip:** A good technique is to define everything using `let` and only change it to `var` if the compiler complains! + +You can define constants on a type rather than on an instance of that type using type properties. To declare a type property as a constant simply use `static let`. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example: + +**Preferred**: +```swift +enum Math { + static let e = 2.718281828459045235360287 + static let root2 = 1.41421356237309504880168872 +} + +let hypotenuse = side * Math.root2 + +``` +**Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace. + +**Not Preferred**: +```swift +let e = 2.718281828459045235360287 // pollutes global namespace +let root2 = 1.41421356237309504880168872 + +let hypotenuse = side * root2 // what is root2? +``` + +### Static Methods and Variable Type Properties + +Static methods and type properties work similarly to global functions and global variables and should be used sparingly. They are useful when functionality is scoped to a particular type or when Objective-C interoperability is required. + +### Optionals + +Declare variables and function return types as optional with `?` where a `nil` value is acceptable. + +Use implicitly unwrapped types declared with `!` only for instance variables that you know will be initialized later before use, such as subviews that will be set up in `viewDidLoad()`. Prefer optional binding to implicitly unwrapped optionals in most other cases. + +When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain: + +```swift +textContainer?.textLabel?.setNeedsDisplay() +``` + +Use optional binding when it's more convenient to unwrap once and perform multiple operations: + +```swift +if let textContainer = textContainer { + // do many things with textContainer +} +``` + +When naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration. + +For optional binding, shadow the original name whenever possible rather than using names like `unwrappedView` or `actualLabel`. + +**Preferred**: +```swift +var subview: UIView? +var volume: Double? + +// later on... +if let subview = subview, let volume = volume { + // do something with unwrapped subview and volume +} + +// another example +resource.request().onComplete { [weak self] response in + guard let self = self else { return } + let model = self.updateModel(response) + self.updateUI(model) +} +``` + +**Not Preferred**: +```swift +var optionalSubview: UIView? +var volume: Double? + +if let unwrappedSubview = optionalSubview { + if let realVolume = volume { + // do something with unwrappedSubview and realVolume + } +} + +// another example +UIView.animate(withDuration: 2.0) { [weak self] in + guard let strongSelf = self else { return } + strongSelf.alpha = 1.0 +} +``` + +### Lazy Initialization + +Consider using lazy initialization for finer grained control over object lifetime. This is especially true for `UIViewController` that loads views lazily. You can either use a closure that is immediately called `{ }()` or call a private factory method. Example: + +```swift +lazy var locationManager = makeLocationManager() + +private func makeLocationManager() -> CLLocationManager { + let manager = CLLocationManager() + manager.desiredAccuracy = kCLLocationAccuracyBest + manager.delegate = self + manager.requestAlwaysAuthorization() + return manager +} +``` + +**Notes:** + - `[unowned self]` is not required here. A retain cycle is not created. + - Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here. + + +### Type Inference + +Prefer compact code and let the compiler infer the type for constants or variables of single instances. Type inference is also appropriate for small, non-empty arrays and dictionaries. When required, specify the specific type such as `CGFloat` or `Int16`. + +**Preferred**: +```swift +let message = "Click the button" +let currentBounds = computeViewBounds() +var names = ["Mic", "Sam", "Christine"] +let maximumWidth: CGFloat = 106.5 +``` + +**Not Preferred**: +```swift +let message: String = "Click the button" +let currentBounds: CGRect = computeViewBounds() +var names = [String]() +``` + +#### Type Annotation for Empty Arrays and Dictionaries + +For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.) + +**Preferred**: +```swift +var names: [String] = [] +var lookup: [String: Int] = [:] +``` + +**Not Preferred**: +```swift +var names = [String]() +var lookup = [String: Int]() +``` + +**NOTE**: Following this guideline means picking descriptive names is even more important than before. + + +### Syntactic Sugar + +Prefer the shortcut versions of type declarations over the full generics syntax. + +**Preferred**: +```swift +var deviceModels: [String] +var employees: [Int: String] +var faxNumber: Int? +``` + +**Not Preferred**: +```swift +var deviceModels: Array +var employees: Dictionary +var faxNumber: Optional +``` + +## Functions vs Methods + +Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability. + +Free functions are most appropriate when they aren't associated with any particular type or instance. + +**Preferred** +```swift +let sorted = items.mergeSorted() // easily discoverable +rocket.launch() // acts on the model +``` + +**Not Preferred** +```swift +let sorted = mergeSort(items) // hard to discover +launch(&rocket) +``` + +**Free Function Exceptions** +```swift +let tuples = zip(a, b) // feels natural as a free function (symmetry) +let value = max(x, y, z) // another free function that feels natural +``` + +## Memory Management + +Code (even non-production, tutorial demo code) should not create reference cycles. Analyze your object graph and prevent strong cycles with `weak` and `unowned` references. Alternatively, use value types (`struct`, `enum`) to prevent cycles altogether. + +### Extending object lifetime + +Extend object lifetime using the `[weak self]` and `guard let self = self else { return }` idiom. `[weak self]` is preferred to `[unowned self]` where it is not immediately obvious that `self` outlives the closure. Explicitly extending lifetime is preferred to optional chaining. + +**Preferred** +```swift +resource.request().onComplete { [weak self] response in + guard let self = self else { + return + } + let model = self.updateModel(response) + self.updateUI(model) +} +``` + +**Not Preferred** +```swift +// might crash if self is released before response returns +resource.request().onComplete { [unowned self] response in + let model = self.updateModel(response) + self.updateUI(model) +} +``` + +**Not Preferred** +```swift +// deallocate could happen between updating the model and updating UI +resource.request().onComplete { [weak self] response in + let model = self?.updateModel(response) + self?.updateUI(model) +} +``` + +## Access Control + +Full access control annotation in tutorials can distract from the main topic and is not required. Using `private` and `fileprivate` appropriately, however, adds clarity and promotes encapsulation. Prefer `private` to `fileprivate`; use `fileprivate` only when the compiler insists. + +Only explicitly use `open`, `public`, and `internal` when you require a full access control specification. + +Use access control as the leading property specifier. The only things that should come before access control are the `static` specifier or attributes such as `@IBAction`, `@IBOutlet` and `@discardableResult`. + +**Preferred**: +```swift +private let message = "Great Scott!" + +class TimeMachine { + private dynamic lazy var fluxCapacitor = FluxCapacitor() +} +``` + +**Not Preferred**: +```swift +fileprivate let message = "Great Scott!" + +class TimeMachine { + lazy dynamic private var fluxCapacitor = FluxCapacitor() +} +``` + +## Control Flow + +Prefer the `for-in` style of `for` loop over the `while-condition-increment` style. + +**Preferred**: +```swift +for _ in 0..<3 { + print("Hello three times") +} + +for (index, person) in attendeeList.enumerated() { + print("\(person) is at position #\(index)") +} + +for index in stride(from: 0, to: items.count, by: 2) { + print(index) +} + +for index in (0...3).reversed() { + print(index) +} +``` + +**Not Preferred**: +```swift +var i = 0 +while i < 3 { + print("Hello three times") + i += 1 +} + + +var i = 0 +while i < attendeeList.count { + let person = attendeeList[i] + print("\(person) is at position #\(i)") + i += 1 +} +``` + +### Ternary Operator + +The Ternary operator, `?:` , should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an `if` statement or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use. + +**Preferred**: + +```swift +let value = 5 +result = value != 0 ? x : y + +let isHorizontal = true +result = isHorizontal ? x : y +``` + +**Not Preferred**: + +```swift +result = a > b ? x = c > d ? c : d : y +``` + +## Golden Path + +When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nest `if` statements. Multiple return statements are OK. The `guard` statement is built for this. + +**Preferred**: +```swift +func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { + guard let context = context else { + throw FFTError.noContext + } + guard let inputData = inputData else { + throw FFTError.noInputData + } + + // use context and input to compute the frequencies + return frequencies +} +``` + +**Not Preferred**: +```swift +func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { + if let context = context { + if let inputData = inputData { + // use context and input to compute the frequencies + + return frequencies + } else { + throw FFTError.noInputData + } + } else { + throw FFTError.noContext + } +} +``` + +When multiple optionals are unwrapped either with `guard` or `if let`, minimize nesting by using the compound version when possible. In the compound version, place the `guard` on its own line, then indent each condition on its own line. The `else` clause is indented to match the `guard` itself, as shown below. Example: + +**Preferred**: +```swift +guard + let number1 = number1, + let number2 = number2, + let number3 = number3 +else { + fatalError("impossible") +} +// do something with numbers +``` + +**Not Preferred**: +```swift +if let number1 = number1 { + if let number2 = number2 { + if let number3 = number3 { + // do something with numbers + } else { + fatalError("impossible") + } + } else { + fatalError("impossible") + } +} else { + fatalError("impossible") +} +``` + +### Failing Guards + +Guard statements are required to exit in some way. Generally, this should be simple one line statement such as `return`, `throw`, `break`, `continue`, and `fatalError()`. Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using a `defer` block to avoid cleanup code duplication. + +## Semicolons + +Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line. + +Do not write multiple statements on a single line separated with semicolons. + +**Preferred**: +```swift +let swift = "not a scripting language" +``` + +**Not Preferred**: +```swift +let swift = "not a scripting language"; +``` + +**NOTE**: Swift is very different from JavaScript, where omitting semicolons is [generally considered unsafe](http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) + +## Parentheses + +Parentheses around conditionals are not required and should be omitted. + +**Preferred**: +```swift +if name == "Hello" { + print("World") +} +``` + +**Not Preferred**: +```swift +if (name == "Hello") { + print("World") +} +``` + +In larger expressions, optional parentheses can sometimes make code read more clearly. + +**Preferred**: +```swift +let playerMark = (player == current ? "X" : "O") +``` + +## Multi-line String Literals + +When building a long string literal, you're encouraged to use the multi-line string literal syntax. Open the literal on the same line as the assignment but do not include text on that line. Indent the text block one additional level. + +**Preferred**: + +```swift +let message = """ + You cannot charge the flux \ + capacitor with a 9V battery. + You must use a super-charger \ + which costs 10 credits. You currently \ + have \(credits) credits available. + """ +``` + +**Not Preferred**: + +```swift +let message = """You cannot charge the flux \ + capacitor with a 9V battery. + You must use a super-charger \ + which costs 10 credits. You currently \ + have \(credits) credits available. + """ +``` + +**Not Preferred**: + +```swift +let message = "You cannot charge the flux " + + "capacitor with a 9V battery.\n" + + "You must use a super-charger " + + "which costs 10 credits. You currently " + + "have \(credits) credits available." +``` + +## No Emoji + +Do not use emoji in your projects. For those readers who actually type in their code, it's an unnecessary source of friction. While it may be cute, it doesn't add to the learning and it interrupts the coding flow for these readers. + +## No #imageLiteral or #colorLiteral + +Likewise, do not use Xcode's ability to drag a color or an image into a source statement. These turn into #colorLiteral and #imageLiteral, respectively, and present unpleasant challenges for a reader trying to enter them based on tutorial text. Instead, use `UIColor(red:green:blue)` and `UIImage(imageLiteralResourceName:)`. + +## Assertions and Fatal Errors We use fatal errors when the app reaches a state that shouldn't happen in a release build and isn't handled, for example, if we fail to instantiate a view controller from a storyboard. We use assert() and assertionFailure() also for when something happens that shouldn't, but when the resulting app state is explicitly handled and is recoverable. -### Unit test names +## Logging + +We use [unified logging system](https://developer.apple.com/documentation/os/logging) to capture log messages. To send a message to the logging system, call the `os_log` function. Please use debug log level to protect users' privacy. + +## Unit Test Names * We use the when then convention for test: