diff --git a/.swiftformat b/.swiftformat index 3e13ecd63..7260cfbb6 100644 --- a/.swiftformat +++ b/.swiftformat @@ -1,4 +1,4 @@ ---swiftversion 5.3 +--swiftversion 5.8 --exclude vendor,Pods,**/Swiftgen/**,**/Resources/**,fastlane,**/Assets/** diff --git a/Sources/App/AppDelegate.swift b/Sources/App/AppDelegate.swift index 9a91c39d0..edb6667fa 100644 --- a/Sources/App/AppDelegate.swift +++ b/Sources/App/AppDelegate.swift @@ -35,7 +35,7 @@ extension AppEnvironment { } } -@UIApplicationMain +@main class AppDelegate: UIResponder, UIApplicationDelegate { @available(iOS, deprecated: 13.0) var window: UIWindow? { @@ -144,12 +144,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } } - @objc internal func openAbout() { + @objc func openAbout() { precondition(Current.sceneManager.supportsMultipleScenes) sceneManager.activateAnyScene(for: .about) } - @objc internal func openMenuUrl(_ command: AnyObject) { + @objc func openMenuUrl(_ command: AnyObject) { guard let command = command as? UICommand, let url = MenuManager.url(from: command) else { return } @@ -160,18 +160,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } } - @objc internal func openPreferences() { + @objc func openPreferences() { precondition(Current.sceneManager.supportsMultipleScenes) sceneManager.activateAnyScene(for: .settings) } - @objc internal func openActionsPreferences() { + @objc func openActionsPreferences() { precondition(Current.sceneManager.supportsMultipleScenes) let delegate: Guarantee = sceneManager.scene(for: .init(activity: .settings)) delegate.done { $0.pushActions(animated: true) } } - @objc internal func openHelp() { + @objc func openHelp() { openURLInBrowser( URL(string: "https://companion.home-assistant.io")!, nil diff --git a/Sources/App/ClientEvents/ClientEventTableViewController.swift b/Sources/App/ClientEvents/ClientEventTableViewController.swift index 06e1ac4d2..d582e3d29 100644 --- a/Sources/App/ClientEvents/ClientEventTableViewController.swift +++ b/Sources/App/ClientEvents/ClientEventTableViewController.swift @@ -112,7 +112,7 @@ public extension ClientEventTableViewController { } extension UITableView { - func applyChanges(changes: RealmCollectionChange) { + func applyChanges(changes: RealmCollectionChange) { switch changes { case .initial: reloadData() case let .update(_, deletions, insertions, updates): diff --git a/Sources/App/ClientEvents/LocationHistoryListViewController.swift b/Sources/App/ClientEvents/LocationHistoryListViewController.swift index d99266c2d..21ad71e28 100644 --- a/Sources/App/ClientEvents/LocationHistoryListViewController.swift +++ b/Sources/App/ClientEvents/LocationHistoryListViewController.swift @@ -82,7 +82,7 @@ extension LocationHistoryListViewController: LocationHistoryDetailMoveDelegate { from row: RowOf, in direction: LocationHistoryDetailViewController.MoveDirection ) -> ButtonRowWithPresent? { - guard let indexPath = row.indexPath, let section = section else { + guard let indexPath = row.indexPath, let section else { return nil } @@ -94,7 +94,7 @@ extension LocationHistoryListViewController: LocationHistoryDetailMoveDelegate { default: nextIndex = nil } - if let nextIndex = nextIndex { + if let nextIndex { return section[nextIndex] as? ButtonRowWithPresent } else { return nil @@ -112,7 +112,7 @@ extension LocationHistoryListViewController: LocationHistoryDetailMoveDelegate { _ controller: LocationHistoryDetailViewController, move direction: LocationHistoryDetailViewController.MoveDirection ) { - guard let navigationController = navigationController, + guard let navigationController, let nextRow = row(from: controller.row, in: direction), let nextController = nextRow.presentationMode?.makeController() else { return diff --git a/Sources/App/Notifications/NotificationManagerLocalPushInterfaceExtension.swift b/Sources/App/Notifications/NotificationManagerLocalPushInterfaceExtension.swift index 2effd2b9a..a3840f803 100644 --- a/Sources/App/Notifications/NotificationManagerLocalPushInterfaceExtension.swift +++ b/Sources/App/Notifications/NotificationManagerLocalPushInterfaceExtension.swift @@ -62,7 +62,7 @@ final class NotificationManagerLocalPushInterfaceExtension: NSObject, Notificati override init() { super.init() - syncStates = PerServerContainer(constructor: { server in + self.syncStates = PerServerContainer(constructor: { server in let sync = LocalPushStateSync(settingsKey: PushProviderConfiguration.defaultSettingsKey(for: server)) let token = sync.observe { [weak self] _ in self?.notifyObservers(for: [server]) @@ -93,7 +93,7 @@ final class NotificationManagerLocalPushInterfaceExtension: NSObject, Notificati Current.Log.info("configuring push for \(ssid): \(servers)") let existing = managers?.first(where: { $0.matchSSIDs == [ssid] }) - if let existing = existing { + if let existing { usedManagers.insert(existing) } updatedManagers.append(updateManager( diff --git a/Sources/App/Onboarding/API/OnboardingAuthError.swift b/Sources/App/Onboarding/API/OnboardingAuthError.swift index 08fc21e9a..8c04e8cc4 100644 --- a/Sources/App/Onboarding/API/OnboardingAuthError.swift +++ b/Sources/App/Onboarding/API/OnboardingAuthError.swift @@ -92,7 +92,7 @@ struct OnboardingAuthError: LocalizedError { extraInfo = nil } - if let extraInfo = extraInfo { + if let extraInfo { return extraInfo + "\n\n" + underlying.localizedDescription } else { return underlying.localizedDescription @@ -101,7 +101,7 @@ struct OnboardingAuthError: LocalizedError { } var responseString: String? { - guard let data = data, let dataString = String(data: data, encoding: .utf8) else { + guard let data, let dataString = String(data: data, encoding: .utf8) else { return nil } diff --git a/Sources/App/Onboarding/API/Steps/OnboardingAuthStepConnectivity.swift b/Sources/App/Onboarding/API/Steps/OnboardingAuthStepConnectivity.swift index 0d870da36..5df3924a3 100644 --- a/Sources/App/Onboarding/API/Steps/OnboardingAuthStepConnectivity.swift +++ b/Sources/App/Onboarding/API/Steps/OnboardingAuthStepConnectivity.swift @@ -37,7 +37,7 @@ class OnboardingAuthStepConnectivity: NSObject, OnboardingAuthPreStep, URLSessio let (requestPromise, requestResolver) = Promise<(data: Data, response: URLResponse)>.pending() let task = session.dataTask(with: authDetails.url) { data, response, error in - if let data = data, let response = response { + if let data, let response { requestResolver.fulfill((data, response)) } else { requestResolver.resolve(nil, error) diff --git a/Sources/App/Onboarding/API/Steps/OnboardingAuthStepDuplicate.swift b/Sources/App/Onboarding/API/Steps/OnboardingAuthStepDuplicate.swift index 42a03f5d1..7dd284cfe 100644 --- a/Sources/App/Onboarding/API/Steps/OnboardingAuthStepDuplicate.swift +++ b/Sources/App/Onboarding/API/Steps/OnboardingAuthStepDuplicate.swift @@ -116,7 +116,7 @@ struct OnboardingAuthStepDuplicate: OnboardingAuthPostStep { handler: { [self] _ in let name = alert.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) - guard let name = name, name.isEmpty == false, + guard let name, name.isEmpty == false, !registeredDevices.contains(where: { $0.matches(name: name) }) else { promptForDeviceName( deviceName: deviceName, diff --git a/Sources/App/Onboarding/Screens/OnboardingManualURLViewController.swift b/Sources/App/Onboarding/Screens/OnboardingManualURLViewController.swift index c23740f60..4bcfb6b7e 100644 --- a/Sources/App/Onboarding/Screens/OnboardingManualURLViewController.swift +++ b/Sources/App/Onboarding/Screens/OnboardingManualURLViewController.swift @@ -175,7 +175,7 @@ class OnboardingManualURLViewController: UIViewController, UITextFieldDelegate { let alert = UIAlertController( title: L10n.Onboarding.ManualSetup.CouldntMakeUrl.title, - message: L10n.Onboarding.ManualSetup.CouldntMakeUrl.message(self.urlField.text ?? ""), + message: L10n.Onboarding.ManualSetup.CouldntMakeUrl.message(urlField.text ?? ""), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: L10n.okLabel, style: UIAlertAction.Style.default, handler: nil)) @@ -266,7 +266,7 @@ class OnboardingManualURLViewController: UIViewController, UITextFieldDelegate { } @objc private func keyboardWillChangeFrame(_ note: Notification) { - guard let scrollView = scrollView, + guard let scrollView, let frameValue = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } diff --git a/Sources/App/Scenes/SceneManager.swift b/Sources/App/Scenes/SceneManager.swift index 3f6fefee4..38008522a 100644 --- a/Sources/App/Scenes/SceneManager.swift +++ b/Sources/App/Scenes/SceneManager.swift @@ -57,7 +57,7 @@ class SceneManager { } } - func resolve(with possible: T) { + func resolve(with possible: some Any) { handleBlock(possible) } } @@ -77,13 +77,13 @@ class SceneManager { init() { Current.realmFatalPresentation = { [weak self] viewController in - guard let self = self else { return } + guard let self else { return } let under = UIViewController() under.view.backgroundColor = .black under.modalPresentationStyle = .fullScreen - self.webViewWindowControllerPromise.done { parent in + webViewWindowControllerPromise.done { parent in parent.present(under, animated: false, completion: { under.present(viewController, animated: true, completion: nil) }) diff --git a/Sources/App/Scenes/SettingsSceneDelegate.swift b/Sources/App/Scenes/SettingsSceneDelegate.swift index 90b3281a1..0210cf7b5 100644 --- a/Sources/App/Scenes/SettingsSceneDelegate.swift +++ b/Sources/App/Scenes/SettingsSceneDelegate.swift @@ -6,7 +6,7 @@ import UIKit @objc class SettingsSceneDelegate: BasicSceneDelegate { private var navigationController: UINavigationController? { didSet { - if let navigationController = navigationController { + if let navigationController { navigationController.delegate = self update(navigationController: navigationController) } @@ -155,7 +155,7 @@ extension SettingsSceneDelegate: NSToolbarDelegate { } fileprivate func selectItemForIdentifier(_ identifier: NSToolbarItem.Identifier) { - if let viewController = viewController(for: identifier), let navigationController = navigationController { + if let viewController = viewController(for: identifier), let navigationController { scene?.title = SettingsRootDataSource.buttonRows.first(where: { $0.tag == identifier.rawValue })?.title // before, so it can be reset by the controller diff --git a/Sources/App/Scenes/WindowScenesManager.swift b/Sources/App/Scenes/WindowScenesManager.swift index 120d3c557..385e4fbc7 100644 --- a/Sources/App/Scenes/WindowScenesManager.swift +++ b/Sources/App/Scenes/WindowScenesManager.swift @@ -37,7 +37,7 @@ final class WindowScenesManager { } // Create cascade effect so windows don't overlap - internal func adjustedSystemFrame( + func adjustedSystemFrame( _ systemFrame: CGRect, for screenSize: CGSize, numberOfConnectedScenes: Int diff --git a/Sources/App/Servers/ServerSelectViewController.swift b/Sources/App/Servers/ServerSelectViewController.swift index 90787b616..f57c68929 100644 --- a/Sources/App/Servers/ServerSelectViewController.swift +++ b/Sources/App/Servers/ServerSelectViewController.swift @@ -77,7 +77,7 @@ class ServerSelectViewController: HAFormViewController, ServerObserver, UIAdapti private func setupForm() { form.removeAll() - if let prompt = prompt, !prompt.isEmpty { + if let prompt, !prompt.isEmpty { form +++ InfoLabelRow { $0.title = prompt } diff --git a/Sources/App/Settings/ActionConfigurator.swift b/Sources/App/Settings/ActionConfigurator.swift index 6f68743ca..521d028f5 100644 --- a/Sources/App/Settings/ActionConfigurator.swift +++ b/Sources/App/Settings/ActionConfigurator.swift @@ -28,7 +28,7 @@ class ActionConfigurator: HAFormViewController, TypedRowControllerType { self.isModalInPresentation = true - if let action = action { + if let action { self.action = Action(value: action) self.newAction = false } else if let firstServer = Current.servers.all.first { @@ -61,8 +61,8 @@ class ActionConfigurator: HAFormViewController, TypedRowControllerType { guard let self else { return } cell.backgroundColor = UIColor.clear cell.preservesSuperviewLayoutMargins = false - self.updatePreviews() - cell.view = self.preview + updatePreviews() + cell.view = preview } let firstSection = Section() @@ -367,7 +367,7 @@ class ActionPreview: UIView { } @objc func handleGesture(gesture: UITapGestureRecognizer) { - guard let action = action, + guard let action, let server = Current.servers.server(forServerIdentifier: action.serverIdentifier) else { return } diff --git a/Sources/App/Settings/AppleWatch/ComplicationFamilySelectViewController.swift b/Sources/App/Settings/AppleWatch/ComplicationFamilySelectViewController.swift index ded7bca8d..354fe817b 100644 --- a/Sources/App/Settings/AppleWatch/ComplicationFamilySelectViewController.swift +++ b/Sources/App/Settings/AppleWatch/ComplicationFamilySelectViewController.swift @@ -74,14 +74,14 @@ class ComplicationFamilySelectViewController: HAFormViewController, RowControlle return ComplicationEditViewController(config: complication) }, onDismiss: { [weak self] vc in - guard let self = self, let vc = vc as? ComplicationEditViewController else { return } + guard let self, let vc = vc as? ComplicationEditViewController else { return } if vc.config.realm == nil { // not saved - self.navigationController?.popViewController(animated: true) + navigationController?.popViewController(animated: true) } else { // saved - self.onDismissCallback?(self) + onDismissCallback?(self) } }) } diff --git a/Sources/App/Settings/Connection/ConnectionSettingsViewController.swift b/Sources/App/Settings/Connection/ConnectionSettingsViewController.swift index 808060989..d85858dff 100644 --- a/Sources/App/Settings/Connection/ConnectionSettingsViewController.swift +++ b/Sources/App/Settings/Connection/ConnectionSettingsViewController.swift @@ -74,7 +74,7 @@ class ConnectionSettingsViewController: HAFormViewController, RowControllerType let manager = Current.notificationManager.localPushManager let updateValue = { [weak row, server] in - guard let row = row else { return } + guard let row else { return } switch manager.status(for: server) { case .disabled: row.value = L10n.SettingsDetails.Notifications.LocalPush.Status.disabled @@ -124,7 +124,7 @@ class ConnectionSettingsViewController: HAFormViewController, RowControllerType var timer: Timer? $0.onChange { [server] row in - if let timer = timer, timer.isValid { + if let timer, timer.isValid { timer.fireDate = Current.date().addingTimeInterval(1.0) } else { timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { _ in diff --git a/Sources/App/Settings/Connection/ConnectionURLViewController.swift b/Sources/App/Settings/Connection/ConnectionURLViewController.swift index dd99c931e..92fcee77e 100644 --- a/Sources/App/Settings/Connection/ConnectionURLViewController.swift +++ b/Sources/App/Settings/Connection/ConnectionURLViewController.swift @@ -69,11 +69,11 @@ final class ConnectionURLViewController: HAFormViewController, TypedRowControlle server.update { info in info.connection.set(address: givenURL, for: urlType) - if let useCloud = useCloud { + if let useCloud { info.connection.useCloud = useCloud } - if let localPush = localPush { + if let localPush { info.connection.isLocalPushEnabled = localPush } @@ -105,7 +105,7 @@ final class ConnectionURLViewController: HAFormViewController, TypedRowControlle return Current.webhooks.sendTest(server: server, baseURL: url) } - if let givenURL = givenURL, useCloud != true { + if let givenURL, useCloud != true { return Current.webhooks.sendTest(server: server, baseURL: givenURL) } @@ -299,7 +299,7 @@ final class ConnectionURLViewController: HAFormViewController, TypedRowControlle locationManager?.delegate = permissionDelegate section.hidden = .function([], { _ in - if let locationManager = locationManager { + if let locationManager { return locationManager.authorizationStatus == .authorizedAlways && locationManager.accuracyAuthorization == .fullAccuracy } else { diff --git a/Sources/App/Settings/DebugSettingsViewController.swift b/Sources/App/Settings/DebugSettingsViewController.swift index 8a4904b05..b31f73ca1 100644 --- a/Sources/App/Settings/DebugSettingsViewController.swift +++ b/Sources/App/Settings/DebugSettingsViewController.swift @@ -170,7 +170,7 @@ class DebugSettingsViewController: HAFormViewController { cell.textLabel?.textAlignment = .natural } }.onCellSelection { [weak self] cell, _ in - guard let self = self else { return } + guard let self else { return } Current.Log.export(from: self, sender: cell, openURLHandler: { url in UIApplication.shared.open(url, options: [:], completionHandler: nil) }) @@ -180,9 +180,9 @@ class DebugSettingsViewController: HAFormViewController { $0.isDestructive = true $0.title = L10n.Settings.ResetSection.ResetWebCache.title $0.onCellSelection { [weak self] _, _ in - guard let self = self else { return } + guard let self else { return } - let hud = MBProgressHUD.showAdded(to: self.view.window ?? self.view, animated: true) + let hud = MBProgressHUD.showAdded(to: view.window ?? view, animated: true) hud.backgroundView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) let (promise, seal) = Guarantee.pending() diff --git a/Sources/App/Settings/Eureka/AccountInitialsImage.swift b/Sources/App/Settings/Eureka/AccountInitialsImage.swift index 4eb8c15ee..4be3aa2f0 100644 --- a/Sources/App/Settings/Eureka/AccountInitialsImage.swift +++ b/Sources/App/Settings/Eureka/AccountInitialsImage.swift @@ -6,7 +6,7 @@ enum AccountInitialsImage { // matching // https://github.com/home-assistant/frontend/blob/42bf350034b7a53f0c6ba76791ea9d2a65bf6d67/src/components/user/ha-user-badge.ts - guard let string = string else { + guard let string else { return "?" } @@ -24,7 +24,7 @@ enum AccountInitialsImage { } static func image(for name: String?, size: CGSize = Self.defaultSize) -> UIImage { - let initials = self.initials(for: name) + let initials = initials(for: name) let rect = CGRect(origin: .zero, size: size) let image = UIGraphicsImageRenderer(size: size).image { context in diff --git a/Sources/App/Settings/Eureka/AccountRow.swift b/Sources/App/Settings/Eureka/AccountRow.swift index 9bb027762..8b708b455 100644 --- a/Sources/App/Settings/Eureka/AccountRow.swift +++ b/Sources/App/Settings/Eureka/AccountRow.swift @@ -65,7 +65,7 @@ class AccountCell: Cell, CellType { let locationName = server.info.name let size = AccountInitialsImage.defaultSize - if let imageView = imageView { + if let imageView { if let image = accountRow?.cachedImage { UIView.transition( with: imageView, @@ -104,7 +104,7 @@ final class HomeAssistantAccountRow: Row, RowType { override func customDidSelect() { super.customDidSelect() if !isDisabled { - if let presentationMode = presentationMode { + if let presentationMode { if let controller = presentationMode.makeController() { presentationMode.present(controller, row: self, presentingController: cell.formViewController()!) } else { @@ -173,10 +173,10 @@ final class HomeAssistantAccountRow: Row, RowType { let connection = api.connection accountSubscription = connection.caches.user.subscribe { [weak self] _, user in - guard let self = self else { return } + guard let self else { return } Current.Log.verbose("got user from user \(user)") - self.cachedUserName = user.name - self.updateCell() + cachedUserName = user.name + updateCell() var lastTask: Request? { didSet { @@ -185,7 +185,7 @@ final class HomeAssistantAccountRow: Row, RowType { } } - self.avatarSubscription = connection.caches.states.subscribe { [weak self] _, states in + avatarSubscription = connection.caches.states.subscribe { [weak self] _, states in firstly { () -> Guarantee> in Guarantee.value(states.all) }.map { states throws -> HAEntity in @@ -202,7 +202,7 @@ final class HomeAssistantAccountRow: Row, RowType { } }.map { path throws -> URL in let url = server.info.connection.activeURL().appendingPathComponent(path) - if let lastTask = lastTask, lastTask.error == nil, lastTask.request?.url == url { + if let lastTask, lastTask.error == nil, lastTask.request?.url == url { throw FetchAvatarError.alreadySet } return url diff --git a/Sources/App/Settings/Eureka/RealmSection.swift b/Sources/App/Settings/Eureka/RealmSection.swift index 5de10655d..728a6ba12 100644 --- a/Sources/App/Settings/Eureka/RealmSection.swift +++ b/Sources/App/Settings/Eureka/RealmSection.swift @@ -67,7 +67,7 @@ public final class RealmSection: Section { } @available(*, unavailable) - required init(_ elements: S) where S: Sequence, S.Element == BaseRow { + required init(_ elements: some Sequence) { fatalError("init(_:) has not been implemented") } diff --git a/Sources/App/Settings/Eureka/SettingsButtonRow.swift b/Sources/App/Settings/Eureka/SettingsButtonRow.swift index d081c5b9a..e2105e0b7 100644 --- a/Sources/App/Settings/Eureka/SettingsButtonRow.swift +++ b/Sources/App/Settings/Eureka/SettingsButtonRow.swift @@ -23,13 +23,13 @@ public final class SettingsButtonRow: _ButtonRowOf, RowType { cell.textLabel?.textColor = .label } - if let icon = icon, !isDestructive { + if let icon, !isDestructive { cell.imageView?.image = icon.settingsIcon(for: cell.traitCollection) } else { cell.imageView?.image = nil } - if let accessoryIcon = accessoryIcon { + if let accessoryIcon { let imageView = cell.accessoryView as? UIImageView ?? UIImageView() let color: UIColor diff --git a/Sources/App/Settings/Eureka/TemplateSection.swift b/Sources/App/Settings/Eureka/TemplateSection.swift index c977a800e..9d2709513 100644 --- a/Sources/App/Settings/Eureka/TemplateSection.swift +++ b/Sources/App/Settings/Eureka/TemplateSection.swift @@ -50,7 +50,7 @@ public final class TemplateSection: Section { } @available(*, unavailable) - required init(_ elements: S) where S: Sequence, S.Element == BaseRow { + required init(_ elements: some Sequence) { fatalError("init(_:) has not been implemented") } diff --git a/Sources/App/Settings/Eureka/YamlSection.swift b/Sources/App/Settings/Eureka/YamlSection.swift index e329493b8..1070f7fd0 100644 --- a/Sources/App/Settings/Eureka/YamlSection.swift +++ b/Sources/App/Settings/Eureka/YamlSection.swift @@ -54,7 +54,7 @@ public final class YamlSection: Section { } @available(*, unavailable) - required init(_ elements: S) where S: Sequence, S.Element == BaseRow { + required init(_ elements: some Sequence) { fatalError("init(_:) has not been implemented") } diff --git a/Sources/App/Settings/NFC/NFCListViewController.swift b/Sources/App/Settings/NFC/NFCListViewController.swift index aed06558d..73d9ac26e 100644 --- a/Sources/App/Settings/NFC/NFCListViewController.swift +++ b/Sources/App/Settings/NFC/NFCListViewController.swift @@ -164,7 +164,7 @@ class NFCListViewController: HAFormViewController { } after(life: textField).done { - if let token = token { + if let token { NotificationCenter.default.removeObserver(token) } token = nil diff --git a/Sources/App/Settings/NFC/NFCReader.swift b/Sources/App/Settings/NFC/NFCReader.swift index b05da2dc8..acfeeac73 100644 --- a/Sources/App/Settings/NFC/NFCReader.swift +++ b/Sources/App/Settings/NFC/NFCReader.swift @@ -62,7 +62,7 @@ class NFCReader: NSObject, NFCTagReaderSessionDelegate { } session.connect(to: tag) { [seal] error in - if let error = error { + if let error { session.invalidate(errorMessage: error.localizedDescription) seal.reject(error) return @@ -76,7 +76,7 @@ class NFCReader: NSObject, NFCTagReaderSessionDelegate { seal.reject(displayError) default: ndefTag.readNDEF { message, error in - if let message = message { + if let message { seal.fulfill(message) session.invalidate() } else { diff --git a/Sources/App/Settings/NFC/NFCWriter.swift b/Sources/App/Settings/NFC/NFCWriter.swift index 3d19ba954..4eceb2695 100644 --- a/Sources/App/Settings/NFC/NFCWriter.swift +++ b/Sources/App/Settings/NFC/NFCWriter.swift @@ -82,7 +82,7 @@ class NFCWriter: NSObject, NFCNDEFReaderSessionDelegate { } tag.queryNDEFStatus { status, capacity, error in - if let error = error { + if let error { session.invalidate(errorMessage: error.localizedDescription) seal.reject(error) return @@ -101,7 +101,7 @@ class NFCWriter: NSObject, NFCNDEFReaderSessionDelegate { } tag.writeNDEF(message) { error in - if let error = error { + if let error { session.invalidate(errorMessage: error.localizedDescription) seal.reject(error) } else { diff --git a/Sources/App/Settings/Notifications/NotificationActionConfigurator.swift b/Sources/App/Settings/Notifications/NotificationActionConfigurator.swift index 3e5e30833..106254353 100644 --- a/Sources/App/Settings/Notifications/NotificationActionConfigurator.swift +++ b/Sources/App/Settings/Notifications/NotificationActionConfigurator.swift @@ -21,7 +21,7 @@ class NotificationActionConfigurator: HAFormViewController, TypedRowControllerTy self.isModalInPresentation = true - if let action = action { + if let action { self.action = action self.newAction = false } @@ -200,7 +200,7 @@ class NotificationActionConfigurator: HAFormViewController, TypedRowControllerTy tag: "exampleTrigger", header: L10n.ActionsConfigurator.TriggerExample.title, yamlGetter: { [weak form, category] in - guard let form = form else { return "" } + guard let form else { return "" } let formVals = form.values(includeHidden: true) diff --git a/Sources/App/Settings/Notifications/NotificationCategoryConfigurator.swift b/Sources/App/Settings/Notifications/NotificationCategoryConfigurator.swift index ab19c824e..0ff43f422 100644 --- a/Sources/App/Settings/Notifications/NotificationCategoryConfigurator.swift +++ b/Sources/App/Settings/Notifications/NotificationCategoryConfigurator.swift @@ -24,7 +24,7 @@ class NotificationCategoryConfigurator: HAFormViewController, TypedRowController self.isModalInPresentation = true - if let category = category { + if let category { self.category = category if self.category.isServerControlled { self.defaultMultivalueOptions = [] @@ -301,7 +301,7 @@ class NotificationCategoryConfigurator: HAFormViewController, TypedRowController var identifier = "new_action_" + UUID().uuidString var title = L10n.NotificationsConfigurator.NewAction.title - if let action = action { + if let action { identifier = action.Identifier title = action.Title } @@ -324,7 +324,7 @@ class NotificationCategoryConfigurator: HAFormViewController, TypedRowController Current.Log.verbose("action \(vc.action)") realm.reentrantWrite { - guard let self = self else { return } + guard let self else { return } // only add into realm if the category is also persisted self.category.realm?.add(vc.action, update: .all) diff --git a/Sources/App/Settings/Notifications/NotificationCategoryListViewController.swift b/Sources/App/Settings/Notifications/NotificationCategoryListViewController.swift index f408d89d9..8132472d7 100644 --- a/Sources/App/Settings/Notifications/NotificationCategoryListViewController.swift +++ b/Sources/App/Settings/Notifications/NotificationCategoryListViewController.swift @@ -78,7 +78,7 @@ class NotificationCategoryListViewController: HAFormViewController { var identifier = "new_category_" + UUID().uuidString var title = L10n.SettingsDetails.Notifications.NewCategory.title - if let category = category { + if let category { identifier = category.Identifier title = category.Name } diff --git a/Sources/App/Settings/Notifications/NotificationRateLimitViewController.swift b/Sources/App/Settings/Notifications/NotificationRateLimitViewController.swift index fb137590f..209dbecc7 100644 --- a/Sources/App/Settings/Notifications/NotificationRateLimitViewController.swift +++ b/Sources/App/Settings/Notifications/NotificationRateLimitViewController.swift @@ -91,7 +91,7 @@ class NotificationRateLimitListViewController: HAFormViewController { } firstly { () -> Promise in - if let initialPromise = initialPromise { + if let initialPromise { self.initialPromise = nil return initialPromise } else { diff --git a/Sources/App/Settings/Notifications/NotificationSettingsViewController.swift b/Sources/App/Settings/Notifications/NotificationSettingsViewController.swift index 32349dc81..cff166f61 100644 --- a/Sources/App/Settings/Notifications/NotificationSettingsViewController.swift +++ b/Sources/App/Settings/Notifications/NotificationSettingsViewController.swift @@ -71,7 +71,7 @@ class NotificationSettingsViewController: HAFormViewController { var lastValue: Int? let update = { [weak row = $0] in - guard let row = row else { return } + guard let row else { return } let value = UIApplication.shared.applicationIconBadgeNumber guard value != lastValue else { return } diff --git a/Sources/App/Settings/Notifications/NotificationSoundsViewController.swift b/Sources/App/Settings/Notifications/NotificationSoundsViewController.swift index 965590f15..4bb341a1c 100644 --- a/Sources/App/Settings/Notifications/NotificationSoundsViewController.swift +++ b/Sources/App/Settings/Notifications/NotificationSoundsViewController.swift @@ -100,7 +100,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe $0.title = L10n.SettingsDetails.Notifications.Sounds.importMacOpenFolder $0.onCellSelection { _, _ in do { - UIApplication.shared.open(try self.librarySoundsURL(), options: [:], completionHandler: nil) + try UIApplication.shared.open(self.librarySoundsURL(), options: [:], completionHandler: nil) } catch { Current.Log.error("couldn't open folder: \(error)") } @@ -263,7 +263,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe Current.Log.verbose("New sound path is \(newSoundPath)") AKConverter(inputURL: pickedURL, outputURL: newSoundPath, options: options).start { error in - if let error = error { + if let error { let sError = SoundError(soundURL: newSoundPath, kind: .conversionFailed, underlying: error) Current.Log.error("Experienced error during convert \(sError) (\(error))") self.showAlert(sError.localizedDescription) @@ -306,7 +306,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe func importedFilesWithSuffix(_ suffix: String) throws -> [URL] { do { let files = try FileManager.default.contentsOfDirectory( - at: try librarySoundsURL(), + at: librarySoundsURL(), includingPropertiesForKeys: nil, options: [] ) @@ -336,7 +336,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe func fileSharingPath() -> Promise { Promise { seal in do { - seal.fulfill(try FileManager.default.url( + try seal.fulfill(FileManager.default.url( for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, @@ -353,7 +353,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe func copySounds(_ soundURLs: [URL], _ formSectionTag: String) throws -> [URL] { guard !soundURLs.isEmpty else { return [URL]() } - let librarySoundsURL = try self.librarySoundsURL() + let librarySoundsURL = try librarySoundsURL() var copiedSounds: [URL] = [] @@ -402,7 +402,7 @@ class NotificationSoundsViewController: HAFormViewController, UIDocumentPickerDe guard !soundURLs.isEmpty else { return Promise.value([URL]()) } do { - let librarySoundsURL = try self.librarySoundsURL() + let librarySoundsURL = try librarySoundsURL() let promises: [Promise] = soundURLs.map { self.copySound(librarySoundsURL, $0, formSectionTag) } diff --git a/Sources/App/Settings/Observation/Action+Observation.swift b/Sources/App/Settings/Observation/Action+Observation.swift index aa56f5a9e..4123a933c 100644 --- a/Sources/App/Settings/Observation/Action+Observation.swift +++ b/Sources/App/Settings/Observation/Action+Observation.swift @@ -43,7 +43,7 @@ extension Action { let updateWatch = Promise { seal in let error = HomeAssistantAPI.SyncWatchContext() - if let error = error { + if let error { seal.reject(error) } else { seal.fulfill(()) diff --git a/Sources/App/Settings/Sensors/SensorDetailViewController.swift b/Sources/App/Settings/Sensors/SensorDetailViewController.swift index 7231d15dd..3a7bebeca 100644 --- a/Sources/App/Settings/Sensors/SensorDetailViewController.swift +++ b/Sources/App/Settings/Sensors/SensorDetailViewController.swift @@ -135,7 +135,7 @@ class SensorDetailViewController: HAFormViewController, SensorObserver { setter(row.value ?? 0) } - if let displayValueFor = displayValueFor { + if let displayValueFor { $0.displayValueFor = displayValueFor } } @@ -147,7 +147,7 @@ class SensorDetailViewController: HAFormViewController, SensorObserver { setter(row.value ?? 0) } - if let displayValueFor = displayValueFor { + if let displayValueFor { $0.displayValueFor = displayValueFor } diff --git a/Sources/App/Settings/SettingsDetailViewController.swift b/Sources/App/Settings/SettingsDetailViewController.swift index 30d228e97..9934df1ce 100644 --- a/Sources/App/Settings/SettingsDetailViewController.swift +++ b/Sources/App/Settings/SettingsDetailViewController.swift @@ -468,10 +468,10 @@ class SettingsDetailViewController: HAFormViewController, TypedRowControllerType with(toggleAllSwitch) { $0.title = L10n.SettingsDetails.Actions.Scenes.selectAll $0.onChange { [weak self] row in - guard let self = self, + guard let self, let value = row.value else { return } - self.realm.reentrantWrite { - scenes.forEach { scene in + realm.reentrantWrite { + for scene in scenes { scene.actionEnabled = value } } diff --git a/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift b/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift index 84b158f8e..9413f23a6 100644 --- a/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift +++ b/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift @@ -33,7 +33,7 @@ final class ThreadClientService: THClientProtocol { // All credentials retrieve the rest of the credentials after user acceps permission dialog // This call may fail, but we don't want to throw error since preferredCredential succeeded - var allCredentials: Set = (try? await client.allCredentials()) ?? [] + var allCredentials: Set = await (try? client.allCredentials()) ?? [] allCredentials = allCredentials.filter { $0.borderAgentID != preferredCredential.borderAgentID } allCredentials.insert(preferredCredential) diff --git a/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingViewModel.swift b/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingViewModel.swift index 86483b86f..9597c6191 100644 --- a/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingViewModel.swift +++ b/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingViewModel.swift @@ -68,11 +68,10 @@ final class ThreadCredentialsSharingViewModel: ObservableObject { case .fulfilled: completion(true) case let .rejected(error): - self - .showAlert(type: .error( - title: L10n.errorLabel, - message: error.localizedDescription - )) + showAlert(type: .error( + title: L10n.errorLabel, + message: error.localizedDescription + )) completion(false) } } diff --git a/Sources/App/Utilities/InputAccessoryView.swift b/Sources/App/Utilities/InputAccessoryView.swift index 44c09ae19..153f94c08 100644 --- a/Sources/App/Utilities/InputAccessoryView.swift +++ b/Sources/App/Utilities/InputAccessoryView.swift @@ -17,12 +17,12 @@ class InputAccessoryView: UIView { var contentView: UIView? { willSet { - if let contentView = contentView, contentView != newValue, contentView.superview == self { + if let contentView, contentView != newValue, contentView.superview == self { contentView.removeFromSuperview() } } didSet { - if let contentView = contentView { + if let contentView { addSubview(contentView) NSLayoutConstraint.activate([ diff --git a/Sources/App/Utilities/NSURL+QueryDictionary.swift b/Sources/App/Utilities/NSURL+QueryDictionary.swift index 094f02698..eb7bbbded 100644 --- a/Sources/App/Utilities/NSURL+QueryDictionary.swift +++ b/Sources/App/Utilities/NSURL+QueryDictionary.swift @@ -1,7 +1,8 @@ import Foundation + extension URL { var queryDictionary: [String: [String]]? { - if let query = query { + if let query { var dictionary = [String: [String]]() for keyValueString in query.components(separatedBy: "&") { diff --git a/Sources/App/Utilities/OpenInChromeController.swift b/Sources/App/Utilities/OpenInChromeController.swift index cbb5c73f6..33abf9d80 100644 --- a/Sources/App/Utilities/OpenInChromeController.swift +++ b/Sources/App/Utilities/OpenInChromeController.swift @@ -40,7 +40,7 @@ private let googleChromeCallbackScheme: String = "googlechrome-x-callback:" private let characterSet: CharacterSet = .urlQueryAllowed private func encodeByAddingPercentEscapes(_ input: String?) -> String { - if let input = input { + if let input { if let percentEncoded = input.addingPercentEncoding(withAllowedCharacters: characterSet) { return percentEncoded } @@ -98,7 +98,7 @@ open class OpenInChromeController { } else if scheme == "https" { chromeScheme = googleChromeHTTPSScheme } - if let chromeScheme = chromeScheme { + if let chromeScheme { let absoluteURLString = url.absoluteString let lowerBound = absoluteURLString.range(of: ":")!.lowerBound let chromeURLString = chromeScheme + absoluteURLString.suffix(from: lowerBound) diff --git a/Sources/App/Utilities/PermissionStatusRow.swift b/Sources/App/Utilities/PermissionStatusRow.swift index b7187f0dd..045498067 100644 --- a/Sources/App/Utilities/PermissionStatusRow.swift +++ b/Sources/App/Utilities/PermissionStatusRow.swift @@ -10,7 +10,7 @@ public final class LocationPermissionRow: Row super.init(tag: tag) displayValueFor = { value in - guard let value = value else { return nil } + guard let value else { return nil } switch value { case .authorizedAlways: @@ -33,7 +33,7 @@ public final class LocationAccuracyRow: Row super.init(tag: tag) displayValueFor = { value in - guard let value = value else { return nil } + guard let value else { return nil } switch value { case .fullAccuracy: return L10n.SettingsDetails.Location.LocationAccuracy.full @@ -50,7 +50,7 @@ public final class MotionPermissionRow: Row>, super.init(tag: tag) displayValueFor = { value in - guard let value = value else { return nil } + guard let value else { return nil } switch value { case .authorized: @@ -71,7 +71,7 @@ public final class FocusPermissionRow: Row Void)?) { INVoiceShortcutCenter.shared.getAllVoiceShortcuts { voiceShortcutsFromCenter, error in - guard let voiceShortcutsFromCenter = voiceShortcutsFromCenter else { - if let error = error { + guard let voiceShortcutsFromCenter else { + if let error { Current.Log.error("Failed to fetch voice shortcuts with error: \(error)") } return } self.voiceShortcuts = voiceShortcutsFromCenter - if let completion = completion { + if let completion { completion() } } diff --git a/Sources/App/Utilities/WebSocketStatusRow.swift b/Sources/App/Utilities/WebSocketStatusRow.swift index 2c1d27812..c835c5201 100644 --- a/Sources/App/Utilities/WebSocketStatusRow.swift +++ b/Sources/App/Utilities/WebSocketStatusRow.swift @@ -53,7 +53,7 @@ public final class WebSocketStatusRow: Row, RowType { case let .waitingToReconnect(lastError: error, atLatest: atLatest, retryCount: count): var components = [String]() - if let error = error { + if let error { components.append(L10n.Settings.ConnectionSection.Websocket.Status.Disconnected.error( error.localizedDescription )) @@ -92,8 +92,8 @@ public final class WebSocketStatusRow: Row, RowType { super.init(tag: tag) displayValueFor = { [weak self] value in - if let value = value, let self = self { - return self.displayStyle.message(for: value) + if let value, let self { + return displayStyle.message(for: value) } else { return nil } @@ -147,7 +147,7 @@ public final class WebSocketStatusRow: Row, RowType { private weak var lastAlertController: UIAlertController? private func presentAlert() { - guard let value = value else { return } + guard let value else { return } let alert = UIAlertController( title: DisplayStyle.alert.title(for: value), diff --git a/Sources/App/WebView/IncomingURLHandler.swift b/Sources/App/WebView/IncomingURLHandler.swift index 95e9eb355..c2400a3c6 100644 --- a/Sources/App/WebView/IncomingURLHandler.swift +++ b/Sources/App/WebView/IncomingURLHandler.swift @@ -69,7 +69,7 @@ class IncomingURLHandler { queryParameters: queryParameters ) }) - } else if let server = server { + } else if let server { windowController.open(from: .deeplink, server: server, urlString: rawURL, skipConfirm: isFromWidget) } else { windowController.openSelectingServer( diff --git a/Sources/App/WebView/ScaleFactorMutator.swift b/Sources/App/WebView/ScaleFactorMutator.swift index 4ef1480de..c4d50a983 100644 --- a/Sources/App/WebView/ScaleFactorMutator.swift +++ b/Sources/App/WebView/ScaleFactorMutator.swift @@ -1,7 +1,7 @@ import Foundation import Shared -class ScaleFactorMutator { +enum ScaleFactorMutator { fileprivate static var sceneIdentifiers = Set() public static func record(sceneIdentifier: String) { swizzleIfNeeded() diff --git a/Sources/App/WebView/Tests/WebViewExternalBusMessageTests.swift b/Sources/App/WebView/Tests/WebViewExternalBusMessageTests.swift index 5bc86651f..5682566f9 100644 --- a/Sources/App/WebView/Tests/WebViewExternalBusMessageTests.swift +++ b/Sources/App/WebView/Tests/WebViewExternalBusMessageTests.swift @@ -1,5 +1,6 @@ @testable import HomeAssistant import XCTest + final class WebViewExternalBusMessageTests: XCTestCase { func test_externalBus_messageKeys() { XCTAssertEqual(WebViewExternalBusMessage.configGet.rawValue, "config/get") diff --git a/Sources/App/WebView/WebViewController.swift b/Sources/App/WebView/WebViewController.swift index f3b354356..e39fda544 100644 --- a/Sources/App/WebView/WebViewController.swift +++ b/Sources/App/WebView/WebViewController.swift @@ -158,7 +158,7 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg webView.addGestureRecognizer(sidebarGestureRecognizer) urlObserver = webView.observe(\.url) { [weak self] webView, _ in - guard let self = self else { return } + guard let self else { return } guard let currentURL = webView.url?.absoluteString.replacingOccurrences(of: "?external_auth=1", with: ""), let cleanURL = URL(string: currentURL), let scheme = cleanURL.scheme else { @@ -170,12 +170,12 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg return } - self.userActivity?.webpageURL = cleanURL - self.userActivity?.userInfo = [ + userActivity?.webpageURL = cleanURL + userActivity?.userInfo = [ RestorableStateKey.lastURL.rawValue: cleanURL, - RestorableStateKey.server.rawValue: self.server.identifier.rawValue, + RestorableStateKey.server.rawValue: server.identifier.rawValue, ] - self.userActivity?.becomeCurrent() + userActivity?.becomeCurrent() } webView.navigationDelegate = self @@ -251,7 +251,7 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg case server(Server) init?(_ userActivity: NSUserActivity?) { - if let userActivity = userActivity { + if let userActivity { self = .userActivity(userActivity) } else { return nil @@ -611,7 +611,7 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg let request: URLRequest if Current.settingsStore.restoreLastURL, - let initialURL = initialURL, initialURL.baseIsEqual(to: webviewURL) { + let initialURL, initialURL.baseIsEqual(to: webviewURL) { Current.Log.info("restoring initial url path: \(initialURL.path)") request = URLRequest(url: initialURL) } else { @@ -823,8 +823,8 @@ final class WebViewController: UIViewController, WKNavigationDelegate, WKUIDeleg withTimeInterval: 5.0, repeats: true, block: { [weak self] timer in - if let self = self, Current.date().timeIntervalSince(timer.fireDate) > 30.0 { - self.sendExternalBus(message: .init(command: "restart")) + if let self, Current.date().timeIntervalSince(timer.fireDate) > 30.0 { + sendExternalBus(message: .init(command: "restart")) } if UIApplication.shared.applicationState == .active { @@ -909,7 +909,7 @@ extension WebViewController: WKScriptMessageHandler { // Current.Log.verbose("Responding to getExternalAuth with: \(callbackName)(true, \(jsonString))") let script = "\(callbackName)(true, \(jsonString))" self.webView.evaluateJavaScript(script, completionHandler: { result, error in - if let error = error { + if let error { Current.Log.error("Failed to trigger getExternalAuth callback: \(error)") } @@ -937,7 +937,7 @@ extension WebViewController: WKScriptMessageHandler { self.webView.evaluateJavaScript(script, completionHandler: { _, error in Current.onboardingObservation.needed(.logout) - if let error = error { + if let error { Current.Log.error("Failed calling sign out callback: \(error)") } @@ -1081,7 +1081,7 @@ extension WebViewController: WKScriptMessageHandler { let script = "window.externalBus(\(jsonString))" Current.Log.verbose("sending \(jsonString)") webView.evaluateJavaScript(script, completionHandler: { _, error in - if let error = error { + if let error { Current.Log.error("failed to fire message to externalBus: \(error)") } seal.resolve(error) diff --git a/Sources/App/WebView/WebViewWindowController.swift b/Sources/App/WebView/WebViewWindowController.swift index 4fea114c4..69d4ec731 100644 --- a/Sources/App/WebView/WebViewWindowController.swift +++ b/Sources/App/WebView/WebViewWindowController.swift @@ -40,7 +40,7 @@ class WebViewWindowController { // must be before the seal fires, or it may request during deinit of an old one window.rootViewController = newValue - if let newWebViewController = newWebViewController { + if let newWebViewController { // any kind of ->webviewcontroller is the same, even if we are for some reason replacing an existing one if webViewControllerPromise.isFulfilled { webViewControllerPromise = .value(newWebViewController) @@ -59,7 +59,7 @@ class WebViewWindowController { let navigationController = UINavigationController() navigationController.setNavigationBarHidden(true, animated: false) - if let rootViewController = rootViewController { + if let rootViewController { navigationController.viewControllers = [rootViewController] } return navigationController @@ -166,7 +166,7 @@ class WebViewWindowController { private func selectServer(prompt: String? = nil, includeSettings: Bool = false) -> Promise { let select = ServerSelectViewController() - if let prompt = prompt { + if let prompt { select.prompt = prompt } if includeSettings { @@ -178,7 +178,7 @@ class WebViewWindowController { } let promise = select.result.ensureThen { [weak select] in Guarantee { seal in - if let select = select, select.presentingViewController != nil { + if let select, select.presentingViewController != nil { select.dismiss(animated: true, completion: { seal(()) }) @@ -228,7 +228,7 @@ class WebViewWindowController { } selectServer(prompt: prompt).done { [self] server in - if let server = server { + if let server { open(from: from, server: server, urlString: openUrlRaw, skipConfirm: true) } }.catch { error in @@ -264,9 +264,9 @@ class WebViewWindowController { } let triggerOpen = { [self] in - if let webviewURL = webviewURL { + if let webviewURL { navigate(to: webviewURL, on: server) - } else if let externalURL = externalURL { + } else if let externalURL { openURLInBrowser(externalURL, presentedViewController) } } @@ -364,7 +364,7 @@ class WebViewWindowController { } selectServer(includeSettings: true).done { [self] server in - if let server = server { + if let server { open(server: server) } }.catch { error in @@ -457,7 +457,7 @@ extension WebViewWindowController: OnboardingStateObserver { restorationActivity = nil } - if let controller = controller { + if let controller { updateRootViewController(to: webViewNavigationController(rootViewController: controller)) } } diff --git a/Sources/App/ZoneManager/ZoneManager.swift b/Sources/App/ZoneManager/ZoneManager.swift index 0e8517409..1c1f94742 100644 --- a/Sources/App/ZoneManager/ZoneManager.swift +++ b/Sources/App/ZoneManager/ZoneManager.swift @@ -100,8 +100,8 @@ class ZoneManager { }.get { [weak self] _ in // a location change means we should consider changing our monitored regions // ^ not tap for this side effect because we don't want to do this on failure - guard let self = self else { return } - self.sync(zones: AnyCollection(self.zones)) + guard let self else { return } + sync(zones: AnyCollection(zones)) }.then { Current.clientEventStore.addEvent(ClientEvent( text: "Updated location", diff --git a/Sources/App/ZoneManager/ZoneManagerAccuracyFuzzer.swift b/Sources/App/ZoneManager/ZoneManagerAccuracyFuzzer.swift index 806b69475..7e774d428 100644 --- a/Sources/App/ZoneManager/ZoneManagerAccuracyFuzzer.swift +++ b/Sources/App/ZoneManager/ZoneManagerAccuracyFuzzer.swift @@ -16,7 +16,7 @@ protocol ZoneManagerAccuracyFuzzer { ) -> ZoneManagerAccuracyFuzzerChange? } -extension Sequence where Element == ZoneManagerAccuracyFuzzer { +extension Sequence { func fuzz(location originalLocation: CLLocation, for event: ZoneManagerEvent) -> CLLocation { reduce(originalLocation) { location, fuzzer in if let change = fuzzer.fuzz(for: location, for: event) { diff --git a/Sources/App/ZoneManager/ZoneManagerEvent.swift b/Sources/App/ZoneManager/ZoneManagerEvent.swift index efdacc283..f0c817014 100644 --- a/Sources/App/ZoneManager/ZoneManagerEvent.swift +++ b/Sources/App/ZoneManager/ZoneManagerEvent.swift @@ -30,7 +30,7 @@ struct ZoneManagerEvent: Equatable, CustomStringConvertible { var eventType: EventType var associatedZone: RLMZone? - internal init( + init( eventType: ZoneManagerEvent.EventType, associatedZone: RLMZone? = nil ) { diff --git a/Sources/App/ZoneManager/ZoneManagerProcessor.swift b/Sources/App/ZoneManager/ZoneManagerProcessor.swift index 1a896644b..796408ee7 100644 --- a/Sources/App/ZoneManager/ZoneManagerProcessor.swift +++ b/Sources/App/ZoneManager/ZoneManagerProcessor.swift @@ -74,7 +74,7 @@ class ZoneManagerProcessorImpl: ZoneManagerProcessor { return .value(event.associatedLocation) } }.map { location in - if let location = location { + if let location { return accuracyFuzzers.fuzz(location: location, for: event) } else { return nil @@ -154,7 +154,7 @@ class ZoneManagerProcessorImpl: ZoneManagerProcessor { return ignore(.unknownRegionState) } - guard let zone = zone else { + guard let zone else { return ignore(.unknownRegion) } diff --git a/Sources/App/ZoneManager/ZoneManagerRegionFilter.swift b/Sources/App/ZoneManager/ZoneManagerRegionFilter.swift index 7a11733da..97e09ddca 100644 --- a/Sources/App/ZoneManager/ZoneManagerRegionFilter.swift +++ b/Sources/App/ZoneManager/ZoneManagerRegionFilter.swift @@ -24,7 +24,7 @@ class ZoneManagerRegionFilterImpl: ZoneManagerRegionFilter { self.circular = circular } - init(_ sequence: T) where T.Element == CLRegion { + init(_ sequence: some Sequence) { let counts = sequence.reduce(into: (beacon: 0, circular: 0)) { counts, region in if region is CLCircularRegion { counts.circular += 1 @@ -82,7 +82,7 @@ class ZoneManagerRegionFilterImpl: ZoneManagerRegionFilter { let sourceLocation: CLLocation? let sourceDecision: String - if let lastLocation = lastLocation { + if let lastLocation { sourceLocation = lastLocation sourceDecision = "last_location" } else if let homeLocation = zones.first(where: \.isHome)?.location { @@ -96,7 +96,7 @@ class ZoneManagerRegionFilterImpl: ZoneManagerRegionFilter { // We've exceeded the limit, so we need to start reducing. // We aim to clip off the ones that are further away. let sorted = segmented.sorted { lhs, rhs in - if let sourceLocation = sourceLocation { + if let sourceLocation { // We have a location to compare against, so do distance return lhs.key.location.distance(from: sourceLocation) < rhs.key.location.distance(from: sourceLocation) } else { diff --git a/Sources/Extensions/NotificationContent/CameraStreamMJPEGViewController.swift b/Sources/Extensions/NotificationContent/CameraStreamMJPEGViewController.swift index a721dccbf..8b7eb9539 100644 --- a/Sources/Extensions/NotificationContent/CameraStreamMJPEGViewController.swift +++ b/Sources/Extensions/NotificationContent/CameraStreamMJPEGViewController.swift @@ -111,7 +111,7 @@ class CameraStreamMJPEGViewController: UIViewController, CameraStreamHandler { lastSize = CGSize(width: 16, height: 9) streamer.streamImages(fromURL: url) { [weak self, imageView] image, error in - guard let image = image else { + guard let image else { self?.seal.reject(MJPEGError.networkError(path: path, error: error)) return } diff --git a/Sources/Extensions/NotificationContent/CameraViewController.swift b/Sources/Extensions/NotificationContent/CameraViewController.swift index e0910554b..620e4e1a1 100644 --- a/Sources/Extensions/NotificationContent/CameraViewController.swift +++ b/Sources/Extensions/NotificationContent/CameraViewController.swift @@ -77,7 +77,7 @@ class CameraViewController: UIViewController, NotificationCategory { .compactMap { controllerClass -> () -> Promise in { do { - return .value(try controllerClass.init(api: api, response: result)) + return try .value(controllerClass.init(api: api, response: result)) } catch { return Promise(error: error) } diff --git a/Sources/Extensions/NotificationContent/ImageAttachmentViewController.swift b/Sources/Extensions/NotificationContent/ImageAttachmentViewController.swift index 886174a1e..8914fd628 100644 --- a/Sources/Extensions/NotificationContent/ImageAttachmentViewController.swift +++ b/Sources/Extensions/NotificationContent/ImageAttachmentViewController.swift @@ -28,7 +28,7 @@ class ImageAttachmentViewController: UIViewController, NotificationCategory { let visibleView: ImageViewType required init(api: HomeAssistantAPI, notification: UNNotification, attachmentURL: URL?) throws { - guard let attachmentURL = attachmentURL else { + guard let attachmentURL else { throw ImageAttachmentError.noAttachment } diff --git a/Sources/Extensions/NotificationContent/NotificationViewController.swift b/Sources/Extensions/NotificationContent/NotificationViewController.swift index 4503a16dd..5ca3eee9a 100644 --- a/Sources/Extensions/NotificationContent/NotificationViewController.swift +++ b/Sources/Extensions/NotificationContent/NotificationViewController.swift @@ -117,7 +117,7 @@ class NotificationViewController: UIViewController, UNNotificationContentExtensi ).then { [weak self] controller -> Promise in self?.activeViewController = controller - guard let controller = controller else { + guard let controller else { return .value(()) } diff --git a/Sources/Extensions/NotificationContent/VideoAudioAttachmentViewController.swift b/Sources/Extensions/NotificationContent/VideoAudioAttachmentViewController.swift index 0a068fc0e..d3b9a8752 100644 --- a/Sources/Extensions/NotificationContent/VideoAudioAttachmentViewController.swift +++ b/Sources/Extensions/NotificationContent/VideoAudioAttachmentViewController.swift @@ -15,7 +15,7 @@ class PlayerAttachmentViewController: UIViewController, NotificationCategory { let needsEndSecurityScoped: Bool required init(api: HomeAssistantAPI, notification: UNNotification, attachmentURL: URL?) throws { - guard let attachmentURL = attachmentURL else { + guard let attachmentURL else { throw PlayerAttachmentError.noAttachment } @@ -55,7 +55,7 @@ class PlayerAttachmentViewController: UIViewController, NotificationCategory { oldValue?.view.removeFromSuperview() oldValue?.removeFromParent() - if let videoViewController = videoViewController { + if let videoViewController { view.addSubview(videoViewController.view) videoViewController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ diff --git a/Sources/Extensions/Share/ShareViewController.swift b/Sources/Extensions/Share/ShareViewController.swift index a0a9af317..c07cc2b00 100644 --- a/Sources/Extensions/Share/ShareViewController.swift +++ b/Sources/Extensions/Share/ShareViewController.swift @@ -11,7 +11,7 @@ class ShareViewController: SLComposeServiceViewController { } private func event(api: HomeAssistantAPI) -> Promise<(eventType: String, eventData: [String: String])> { - guard let extensionContext = extensionContext else { + guard let extensionContext else { return .init(error: EventError.invalidExtensionContext) } diff --git a/Sources/Extensions/Watch/ExtensionDelegate.swift b/Sources/Extensions/Watch/ExtensionDelegate.swift index d56a67171..a21e81856 100644 --- a/Sources/Extensions/Watch/ExtensionDelegate.swift +++ b/Sources/Extensions/Watch/ExtensionDelegate.swift @@ -125,7 +125,7 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate { complication = nil } - if let complication = complication { + if let complication { Current.Log.info("launched for \(complication.identifier) of family \(complication.Family)") } else { Current.Log.verbose("unknown or no complication launched the app") diff --git a/Sources/Extensions/Watch/Notifications/NotificationSubControllerMJPEG.swift b/Sources/Extensions/Watch/Notifications/NotificationSubControllerMJPEG.swift index 59799a87f..de6bccdab 100644 --- a/Sources/Extensions/Watch/Notifications/NotificationSubControllerMJPEG.swift +++ b/Sources/Extensions/Watch/Notifications/NotificationSubControllerMJPEG.swift @@ -35,9 +35,9 @@ class NotificationSubControllerMJPEG: NotificationSubController { let queryUrl = apiURL.appendingPathComponent("camera_proxy_stream/\(entityId)", isDirectory: false) streamer.streamImages(fromURL: queryUrl) { uiImage, error in - if let error = error { + if let error { seal.reject(error) - } else if let uiImage = uiImage { + } else if let uiImage { seal.fulfill(()) elements.image.setHidden(false) elements.image.setImage(uiImage) diff --git a/Sources/Extensions/Watch/Notifications/NotificationSubControllerMap.swift b/Sources/Extensions/Watch/Notifications/NotificationSubControllerMap.swift index 25f006cc7..3191f311e 100644 --- a/Sources/Extensions/Watch/Notifications/NotificationSubControllerMap.swift +++ b/Sources/Extensions/Watch/Notifications/NotificationSubControllerMap.swift @@ -40,7 +40,7 @@ class NotificationSubControllerMap: NotificationSubController { elements.map.addAnnotation(location, with: .red) - if let secondLocation = secondLocation { + if let secondLocation { pinLocations.append(secondLocation) elements.map.addAnnotation(secondLocation, with: .green) } diff --git a/Sources/Extensions/Widgets/Common/WidgetBasicView.swift b/Sources/Extensions/Widgets/Common/WidgetBasicView.swift index 53fdabf27..b752fff65 100644 --- a/Sources/Extensions/Widgets/Common/WidgetBasicView.swift +++ b/Sources/Extensions/Widgets/Common/WidgetBasicView.swift @@ -155,7 +155,7 @@ struct WidgetBasicView: View { case .regular, .condensed: HStack(alignment: .center, spacing: 6.0) { icon - if let subtext = subtext { + if let subtext { VStack(alignment: .leading, spacing: -2) { text subtext @@ -172,7 +172,7 @@ struct WidgetBasicView: View { icon Spacer() text - if let subtext = subtext { + if let subtext { subtext } } diff --git a/Sources/Launcher/LauncherAppDelegate.swift b/Sources/Launcher/LauncherAppDelegate.swift index 1691f28a8..dce6b76ca 100644 --- a/Sources/Launcher/LauncherAppDelegate.swift +++ b/Sources/Launcher/LauncherAppDelegate.swift @@ -23,9 +23,9 @@ class LauncherAppDelegate: NSObject, NSApplicationDelegate { openConfiguration.activates = false NSWorkspace.shared.openApplication(at: appURL, configuration: openConfiguration) { [self] app, error in - if let app = app { + if let app { print("launched app: \(app)") - } else if let error = error { + } else if let error { print("failed to launch app: \(error)") } diff --git a/Sources/MacBridge/MacBridgeNetworkMonitor.swift b/Sources/MacBridge/MacBridgeNetworkMonitor.swift index cedd699f1..7dbb02898 100644 --- a/Sources/MacBridge/MacBridgeNetworkMonitor.swift +++ b/Sources/MacBridge/MacBridgeNetworkMonitor.swift @@ -18,7 +18,7 @@ class MacBridgeNetworkMonitor { self.wifiClient = CWWiFiClient.shared() let callback: SCDynamicStoreCallBack = { _, _, context in - guard let context = context else { return } + guard let context else { return } let this = Unmanaged.fromOpaque(context).takeUnretainedValue() this.storeDidChange() } @@ -38,7 +38,7 @@ class MacBridgeNetworkMonitor { } var networkConnectivity: MacBridgeNetworkConnectivityImpl { - if let cachedNetworkConnectivity = cachedNetworkConnectivity { + if let cachedNetworkConnectivity { return cachedNetworkConnectivity } else { let new = newNetworkConnectivity() @@ -78,7 +78,7 @@ class MacBridgeNetworkMonitor { NotificationCenter.default.post(name: Self.connectivityDidChangeNotification, object: nil) } - internal func newNetworkConnectivity() -> MacBridgeNetworkConnectivityImpl { + func newNetworkConnectivity() -> MacBridgeNetworkConnectivityImpl { let primaryInterface = currentInterface let wifiInterfaces = wifiClient.interfaces() ?? [] let wifi: MacBridgeWiFiImpl? = wifiInterfaces.compactMap { interface -> MacBridgeWiFiImpl? in diff --git a/Sources/PushServer/Package.swift b/Sources/PushServer/Package.swift index a1afe5d24..180a3bebf 100644 --- a/Sources/PushServer/Package.swift +++ b/Sources/PushServer/Package.swift @@ -26,7 +26,8 @@ let package = Package( // Enable better optimizations when building in Release configuration. Despite the use of // the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release // builds. See - // for details. + // for + // details. .unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)), ] ), diff --git a/Sources/PushServer/SharedPush/Sources/NotificationParserLegacy.swift b/Sources/PushServer/SharedPush/Sources/NotificationParserLegacy.swift index 372434704..f777ea2ad 100644 --- a/Sources/PushServer/SharedPush/Sources/NotificationParserLegacy.swift +++ b/Sources/PushServer/SharedPush/Sources/NotificationParserLegacy.swift @@ -82,7 +82,7 @@ public struct LegacyNotificationParserImpl: LegacyNotificationParser { } }() - if let commandPayload = commandPayload { + if let commandPayload { var payload = commandPayload.payload if let push = data["push"] as? [String: Any], let badge = push["badge"] as? Int { diff --git a/Sources/PushServer/Sources/App/Controllers/PushController.swift b/Sources/PushServer/Sources/App/Controllers/PushController.swift index cd64d2ee5..3c97c031c 100644 --- a/Sources/PushServer/Sources/App/Controllers/PushController.swift +++ b/Sources/PushServer/Sources/App/Controllers/PushController.swift @@ -140,14 +140,14 @@ class PushController { let sentString = String(decoding: apns.payload, as: UTF8.self) req.logger.debug("sent: \(sentString)") let response = Response(status: .created) - try response.content.encode(PushSendOutput( + await try response.content.encode(PushSendOutput( target: input.pushToken, messageId: messageId, pushType: apns.pushType.rawValue, collapseIdentifier: apns.collapseIdentifier, rateLimits: .init( rateLimits: rateLimits, - resetsAt: await req.application.rateLimits.expirationDate(for: input.pushToken) + resetsAt: req.application.rateLimits.expirationDate(for: input.pushToken) ), sentPayload: sentString )) diff --git a/Sources/PushServer/Sources/App/Controllers/RateLimitsController.swift b/Sources/PushServer/Sources/App/Controllers/RateLimitsController.swift index 4190b1c74..d354a3d1f 100644 --- a/Sources/PushServer/Sources/App/Controllers/RateLimitsController.swift +++ b/Sources/PushServer/Sources/App/Controllers/RateLimitsController.swift @@ -5,13 +5,13 @@ class RateLimitsController { try RateLimitsGetInput.validate(content: req) let input = try req.content.decode(RateLimitsGetInput.self) let rateLimits = try await req.application.rateLimits.rateLimit(for: input.pushToken) - return .init( + return await .init( target: input.pushToken, rateLimits: .init( successful: rateLimits.successful, errors: rateLimits.errors, maximum: RateLimitsValues.dailyMaximum, - resetsAt: await req.application.rateLimits.expirationDate(for: input.pushToken) + resetsAt: req.application.rateLimits.expirationDate(for: input.pushToken) ) ) } diff --git a/Sources/PushServer/Sources/App/Dependencies/Application+NotificationParser.swift b/Sources/PushServer/Sources/App/Dependencies/Application+NotificationParser.swift index a21e63228..18dbffadf 100644 --- a/Sources/PushServer/Sources/App/Dependencies/Application+NotificationParser.swift +++ b/Sources/PushServer/Sources/App/Dependencies/Application+NotificationParser.swift @@ -29,7 +29,7 @@ extension Application.Parser: LegacyNotificationParser { from input: [String: Any], defaultRegistrationInfo: @autoclosure () -> [String: String] ) -> LegacyNotificationParserResult { - if let parser = parser { + if let parser { return parser.result(from: input, defaultRegistrationInfo: defaultRegistrationInfo()) } else { fatalError("parser not configured") diff --git a/Sources/PushServer/Sources/App/Dependencies/Application+RateLimits.swift b/Sources/PushServer/Sources/App/Dependencies/Application+RateLimits.swift index 6a1921a0f..482bd3bd2 100644 --- a/Sources/PushServer/Sources/App/Dependencies/Application+RateLimits.swift +++ b/Sources/PushServer/Sources/App/Dependencies/Application+RateLimits.swift @@ -35,7 +35,7 @@ public extension Application { extension Application.RateLimits: RateLimits { public func expirationDate(for identifier: String) async -> Date { - if let rateLimits = rateLimits { + if let rateLimits { return await rateLimits.expirationDate(for: identifier) } else { fatalError("rate limits not configured before use") @@ -43,7 +43,7 @@ extension Application.RateLimits: RateLimits { } public func rateLimit(for identifier: String) async throws -> RateLimitsValues { - if let rateLimits = rateLimits { + if let rateLimits { return try await rateLimits.rateLimit(for: identifier) } else { fatalError("rate limits not configured before use") @@ -51,7 +51,7 @@ extension Application.RateLimits: RateLimits { } public func increment(kind: RateLimitsIncrementKind, for identifier: String) async throws -> RateLimitsValues { - if let rateLimits = rateLimits { + if let rateLimits { return try await rateLimits.increment(kind: kind, for: identifier) } else { fatalError("rate limits not configured before use") diff --git a/Sources/PushServer/Sources/App/Dependencies/Request+TestableAPNS.swift b/Sources/PushServer/Sources/App/Dependencies/Request+TestableAPNS.swift index 5e0a08a37..da99633c4 100644 --- a/Sources/PushServer/Sources/App/Dependencies/Request+TestableAPNS.swift +++ b/Sources/PushServer/Sources/App/Dependencies/Request+TestableAPNS.swift @@ -16,7 +16,7 @@ extension Request.TestableAPNS: APNSwiftClient { request.application.environment == .testing } - internal struct PendingSend { + struct PendingSend { var promise: EventLoopPromise var payload: ByteBuffer var pushType: APNSwiftConnection.PushType diff --git a/Sources/PushServer/Sources/App/Models/PushSendInput.swift b/Sources/PushServer/Sources/App/Models/PushSendInput.swift index b434760f1..ba2b51f48 100644 --- a/Sources/PushServer/Sources/App/Models/PushSendInput.swift +++ b/Sources/PushServer/Sources/App/Models/PushSendInput.swift @@ -21,7 +21,7 @@ struct PushRegistrationInfo: Content { self.webhookId = try container.decodeIfPresent(String.self, forKey: .webhookId) } - internal init(appId: String, appVersion: String, osVersion: String, webhookId: String?) { + init(appId: String, appVersion: String, osVersion: String, webhookId: String?) { self.appId = appId self.appVersion = appVersion self.osVersion = osVersion @@ -54,7 +54,7 @@ struct PushSendInput: Content { } } - internal init(encrypted: Bool, encryptedData: String?, registrationInfo: PushRegistrationInfo, pushToken: String) { + init(encrypted: Bool, encryptedData: String?, registrationInfo: PushRegistrationInfo, pushToken: String) { self.encrypted = encrypted self.encryptedData = encryptedData self.registrationInfo = registrationInfo diff --git a/Sources/PushServer/Tests/AppTests/Fakes/FakeCache.swift b/Sources/PushServer/Tests/AppTests/Fakes/FakeCache.swift index ca2eeab70..3e07e47cb 100644 --- a/Sources/PushServer/Tests/AppTests/Fakes/FakeCache.swift +++ b/Sources/PushServer/Tests/AppTests/Fakes/FakeCache.swift @@ -14,12 +14,15 @@ final class FakeCache: Cache { eventLoop.makeSucceededFuture(values[key] as? T) } - func set(_ key: String, to value: T?) -> EventLoopFuture where T: Encodable { + func set(_ key: String, to value: (some Encodable)?) -> EventLoopFuture { set(key, to: value, expiresIn: nil) } - func set(_ key: String, to value: T?, expiresIn expirationTime: CacheExpirationTime?) -> EventLoopFuture - where T: Encodable { + func set( + _ key: String, + to value: (some Encodable)?, + expiresIn expirationTime: CacheExpirationTime? + ) -> EventLoopFuture { values[key] = value expirations[key] = value != nil ? expirationTime : nil return eventLoop.makeSucceededFuture(()) diff --git a/Sources/PushServer/Tests/AppTests/RateLimitsTests.swift b/Sources/PushServer/Tests/AppTests/RateLimitsTests.swift index cf3dd77f0..88f6ff5fa 100644 --- a/Sources/PushServer/Tests/AppTests/RateLimitsTests.swift +++ b/Sources/PushServer/Tests/AppTests/RateLimitsTests.swift @@ -25,7 +25,7 @@ class RateLimitsTests: AbstractTestCase { let expirationDate3 = await rateLimits.expirationDate(for: "token3") XCTAssertGreaterThan(expirationDate3, expirationDate2) - let expected = Calendar.current.startOfDay(for: try XCTUnwrap( + let expected = try Calendar.current.startOfDay(for: XCTUnwrap( Calendar.current.date(byAdding: .day, value: 1, to: now, wrappingComponents: false) )).timeIntervalSince(now) XCTAssertGreaterThan(expected, 0) diff --git a/Sources/PushServer/Tests/SharedPushTests/NotificationParserLegacy.test.swift b/Sources/PushServer/Tests/SharedPushTests/NotificationParserLegacy.test.swift index d9186ab0b..84d67eb19 100644 --- a/Sources/PushServer/Tests/SharedPushTests/NotificationParserLegacy.test.swift +++ b/Sources/PushServer/Tests/SharedPushTests/NotificationParserLegacy.test.swift @@ -37,8 +37,8 @@ class NotificationParserLegacyTests: XCTestCase { notificationCases = try enumerator.allObjects .map { try XCTUnwrap($0 as? URL) } .filter { $0.pathExtension == "json" } - .map { ($0.lastPathComponent, try Data(contentsOf: $0)) } - .map { ($0.0, try JSONSerialization.jsonObject(with: $0.1, options: [])) } + .map { try ($0.lastPathComponent, Data(contentsOf: $0)) } + .map { try ($0.0, JSONSerialization.jsonObject(with: $0.1, options: [])) } .map { var notificationCase = try NotificationCase(jsonObject: $0.1) notificationCase.name = $0.0 diff --git a/Sources/Shared/API/Authentication/AuthenticationAPI.swift b/Sources/Shared/API/Authentication/AuthenticationAPI.swift index 18f78f932..ba1932e7d 100644 --- a/Sources/Shared/API/Authentication/AuthenticationAPI.swift +++ b/Sources/Shared/API/Authentication/AuthenticationAPI.swift @@ -101,7 +101,7 @@ extension DataRequest { validate { _, response, data in if case 200 ..< 300 = response.statusCode { return .success(()) - } else if let data = data { + } else if let data { let errorCode: String? let error: String? diff --git a/Sources/Shared/API/Authentication/AuthenticationRoutes.swift b/Sources/Shared/API/Authentication/AuthenticationRoutes.swift index 7d4a7360c..b6b29da8b 100644 --- a/Sources/Shared/API/Authentication/AuthenticationRoutes.swift +++ b/Sources/Shared/API/Authentication/AuthenticationRoutes.swift @@ -18,7 +18,7 @@ enum AuthenticationRoute { func asURLRequestWith(baseURL: URL) throws -> URLRequest { let baseRequest = try URLRequest(url: baseURL.appendingPathComponent(path), method: method) let request: URLRequest - if let parameters = parameters { + if let parameters { request = try URLEncoding.httpBody.encode(baseRequest, with: parameters) } else { request = baseRequest diff --git a/Sources/Shared/API/Authentication/TokenManager.swift b/Sources/Shared/API/Authentication/TokenManager.swift index 206ede0f4..ec14094e3 100644 --- a/Sources/Shared/API/Authentication/TokenManager.swift +++ b/Sources/Shared/API/Authentication/TokenManager.swift @@ -127,7 +127,7 @@ public class TokenManager { refreshPromiseCache.queue.sync { [self, server] in let tokenInfo = server.info.token - if let refreshPromise = self.refreshPromiseCache.promise { + if let refreshPromise = refreshPromiseCache.promise { Current.Log.info("using cached refreshToken promise") return refreshPromise } diff --git a/Sources/Shared/API/ConnectionInfo.swift b/Sources/Shared/API/ConnectionInfo.swift index 3793d42a8..96c2dafd4 100644 --- a/Sources/Shared/API/ConnectionInfo.swift +++ b/Sources/Shared/API/ConnectionInfo.swift @@ -42,7 +42,7 @@ public struct ConnectionInfo: Codable, Equatable { public var securityExceptions: SecurityExceptions = .init() public func evaluate(_ challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) { - return securityExceptions.evaluate(challenge) + securityExceptions.evaluate(challenge) } public init( @@ -150,7 +150,7 @@ public struct ConnectionInfo: Codable, Equatable { /// Returns the url that should be used at this moment to access the Home Assistant instance. public mutating func activeURL() -> URL { - if let overrideActiveURLType = overrideActiveURLType { + if let overrideActiveURLType { let overrideURL: URL? switch overrideActiveURLType { @@ -165,28 +165,28 @@ public struct ConnectionInfo: Codable, Equatable { overrideURL = externalURL } - if let overrideURL = overrideURL { + if let overrideURL { return overrideURL.sanitized() } } let url: URL - if let internalURL = internalURL, isOnInternalNetwork || overrideActiveURLType == .internal { + if let internalURL, isOnInternalNetwork || overrideActiveURLType == .internal { activeURLType = .internal url = internalURL - } else if let remoteUIURL = remoteUIURL, useCloud { + } else if let remoteUIURL, useCloud { activeURLType = .remoteUI url = remoteUIURL - } else if let externalURL = externalURL { + } else if let externalURL { activeURLType = .external url = externalURL } else { // we're missing a url, so try and fall back to one that _could_ work - if let remoteUIURL = remoteUIURL { + if let remoteUIURL { activeURLType = .remoteUI url = remoteUIURL - } else if let internalURL = internalURL { + } else if let internalURL { activeURLType = .internal url = internalURL } else { @@ -204,7 +204,7 @@ public struct ConnectionInfo: Codable, Equatable { } public mutating func webhookURL() -> URL { - if let cloudhookURL = cloudhookURL, !isOnInternalNetwork { + if let cloudhookURL, !isOnInternalNetwork { return cloudhookURL } @@ -251,7 +251,7 @@ public struct ConnectionInfo: Codable, Equatable { /// Secret as byte array func webhookSecretBytes(version: Version) -> [UInt8]? { - guard let webhookSecret = webhookSecret, webhookSecret.count.isMultiple(of: 2) else { + guard let webhookSecret, webhookSecret.count.isMultiple(of: 2) else { return nil } diff --git a/Sources/Shared/API/Fixtures/ServerFixture.swift b/Sources/Shared/API/Fixtures/ServerFixture.swift index 9e79241cd..b10d476ab 100644 --- a/Sources/Shared/API/Fixtures/ServerFixture.swift +++ b/Sources/Shared/API/Fixtures/ServerFixture.swift @@ -1,7 +1,7 @@ import Foundation import Shared -struct ServerFixture { +enum ServerFixture { static var standard = Server(identifier: "123", getter: { .init( name: "A Name", diff --git a/Sources/Shared/API/HAAPI.swift b/Sources/Shared/API/HAAPI.swift index d4ad427d7..6b656334c 100644 --- a/Sources/Shared/API/HAAPI.swift +++ b/Sources/Shared/API/HAAPI.swift @@ -243,7 +243,7 @@ public class HomeAssistantAPI { // using a random file name so we always have one, see https://github.com/home-assistant/iOS/issues/1068 .appendingPathComponent(UUID().uuidString, isDirectory: false) - if let downloadingURL = downloadingURL { + if let downloadingURL { return url.appendingPathExtension(downloadingURL.pathExtension) } else { return url @@ -498,7 +498,7 @@ public class HomeAssistantAPI { case .zoneOnly: if updateType == .BeaconRegionEnter { update = .init(trigger: updateType, usingNameOf: zone) - } else if let rawLocation = rawLocation { + } else if let rawLocation { // note this is a different zone than the event - e.g. the zone may be the one we are exiting update = .init(trigger: updateType, usingNameOf: RLMZone.zone(of: rawLocation, in: server)) } else { @@ -579,13 +579,13 @@ public class HomeAssistantAPI { var eventData: [String: Any] = sharedEventDeviceInfo eventData["actionName"] = identifier - if let category = category { + if let category { eventData["categoryName"] = category } - if let actionData = actionData { + if let actionData { eventData["action_data"] = actionData } - if let textInput = textInput { + if let textInput { eventData["response_info"] = textInput eventData["textInput"] = textInput } @@ -602,10 +602,10 @@ public class HomeAssistantAPI { var eventData = [String: Any]() eventData["action"] = identifier - if let actionData = actionData { + if let actionData { eventData["action_data"] = actionData } - if let textInput = textInput { + if let textInput { eventData["reply_text"] = textInput } @@ -629,7 +629,7 @@ public class HomeAssistantAPI { actionID: String, source: ActionSource ) -> (serviceDomain: String, serviceName: String, serviceData: [String: String]) { - return (serviceDomain: "scene", serviceName: "turn_on", serviceData: ["entity_id": actionID]) + (serviceDomain: "scene", serviceName: "turn_on", serviceData: ["entity_id": actionID]) } public func tagEvent( @@ -780,7 +780,7 @@ public class HomeAssistantAPI { UpdateSensors(trigger: trigger, limitedTo: nil, location: location) } - internal func UpdateSensors( + func UpdateSensors( trigger: LocationUpdateTrigger, limitedTo: [SensorProvider.Type]?, location: CLLocation? = nil diff --git a/Sources/Shared/API/MJPEGStreamer.swift b/Sources/Shared/API/MJPEGStreamer.swift index 6edb6b101..2bc1cb817 100644 --- a/Sources/Shared/API/MJPEGStreamer.swift +++ b/Sources/Shared/API/MJPEGStreamer.swift @@ -114,7 +114,7 @@ public class MJPEGStreamer { case .endOfResponse: let image = UIImage(data: pendingData) pendingData.removeAll(keepingCapacity: true) - if let image = image { + if let image { DispatchQueue.main.async { [self] in callback?(image, nil) } diff --git a/Sources/Shared/API/Models/LocationHistory.swift b/Sources/Shared/API/Models/LocationHistory.swift index cd45cc4dd..e9c2b94b0 100644 --- a/Sources/Shared/API/Models/LocationHistory.swift +++ b/Sources/Shared/API/Models/LocationHistory.swift @@ -30,9 +30,9 @@ public class LocationHistoryEntry: Object { self.init() var loc = CLLocation() - if let location = location { + if let location { loc = location - } else if let zone = zone { + } else if let zone { loc = zone.location } diff --git a/Sources/Shared/API/Models/ModelManager.swift b/Sources/Shared/API/Models/ModelManager.swift index 858801ec8..bf97e5fe4 100644 --- a/Sources/Shared/API/Models/ModelManager.swift +++ b/Sources/Shared/API/Models/ModelManager.swift @@ -282,15 +282,15 @@ public class ModelManager: ServerObserver { }).asVoid() } - internal enum StoreError: Error { + enum StoreError: Error { case missingPrimaryKey } - internal func store( + func store( type realmObjectType: UM.Type, from server: Server, - sourceModels: C - ) -> Promise where C.Element == UM.Source { + sourceModels: some Collection + ) -> Promise { let realm = Current.realm() return realm.reentrantWrite { guard let realmPrimaryKey = realmObjectType.primaryKey() else { diff --git a/Sources/Shared/API/Models/NotificationAction.swift b/Sources/Shared/API/Models/NotificationAction.swift index d7871262b..bc5496ef3 100644 --- a/Sources/Shared/API/Models/NotificationAction.swift +++ b/Sources/Shared/API/Models/NotificationAction.swift @@ -84,7 +84,7 @@ public class NotificationAction: Object { if #available(iOS 15, watchOS 8, *) { let actionIcon: UNNotificationActionIcon? - if let icon = icon, icon.hasPrefix("sfsymbols:") { + if let icon, icon.hasPrefix("sfsymbols:") { actionIcon = .init(systemImageName: icon.replacingOccurrences(of: "sfsymbols:", with: "")) } else { actionIcon = nil diff --git a/Sources/Shared/API/Models/RealmScene.swift b/Sources/Shared/API/Models/RealmScene.swift index 1b76aa262..eee4ecbb2 100644 --- a/Sources/Shared/API/Models/RealmScene.swift +++ b/Sources/Shared/API/Models/RealmScene.swift @@ -26,7 +26,7 @@ public final class RLMScene: Object, UpdatableModel { } set { precondition(realm?.isInWriteTransaction == true) - guard let realm = realm else { return } + guard let realm else { return } backingActionEnabled = newValue updateAction(realm: realm) } @@ -115,15 +115,15 @@ public final class RLMScene: Object, UpdatableModel { action.Name = name ?? identifier action.Text = name ?? identifier - if let backgroundColor = backgroundColor { + if let backgroundColor { action.BackgroundColor = backgroundColor } - if let textColor = textColor { + if let textColor { action.TextColor = textColor } - if let iconColor = iconColor { + if let iconColor { action.IconColor = iconColor } diff --git a/Sources/Shared/API/Models/RealmZone.swift b/Sources/Shared/API/Models/RealmZone.swift index 2000d6492..90f2d7169 100644 --- a/Sources/Shared/API/Models/RealmZone.swift +++ b/Sources/Shared/API/Models/RealmZone.swift @@ -115,7 +115,7 @@ public final class RLMZone: Object, UpdatableModel { public var regionsForMonitoring: [CLRegion] { #if os(iOS) - if let beaconRegion = beaconRegion { + if let beaconRegion { return [beaconRegion] } else { return circularRegionsForMonitoring @@ -239,8 +239,8 @@ public final class RLMZone: Object, UpdatableModel { } public var isBeaconRegion: Bool { - if self.isInvalidated { return false } - return self.BeaconUUID != nil + if isInvalidated { return false } + return BeaconUUID != nil } override public var debugDescription: String { diff --git a/Sources/Shared/API/Models/WatchComplication.swift b/Sources/Shared/API/Models/WatchComplication.swift index 7ce62624e..40d47ea30 100644 --- a/Sources/Shared/API/Models/WatchComplication.swift +++ b/Sources/Shared/API/Models/WatchComplication.swift @@ -202,7 +202,7 @@ public class WatchComplication: Object, ImmutableMappable { return value default: Current.Log.info("unsure how to float-ify \(type(of: value)), trying as a string") - return Self.percentileNumber(from: String(describing: value)) + return percentileNumber(from: String(describing: value)) } } @@ -363,19 +363,19 @@ public class WatchComplication: Object, ImmutableMappable { switch Template { case .CircularSmallRingImage: let template = CLKComplicationTemplateCircularSmallRingImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color return template case .CircularSmallSimpleImage: let template = CLKComplicationTemplateCircularSmallSimpleImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil @@ -383,7 +383,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .CircularSmallStackImage: let template = CLKComplicationTemplateCircularSmallStackImage() - if let iconProvider = iconProvider { + if let iconProvider { template.line1ImageProvider = iconProvider } else { return nil @@ -401,7 +401,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color @@ -429,19 +429,19 @@ public class WatchComplication: Object, ImmutableMappable { return template case .ExtraLargeRingImage: let template = CLKComplicationTemplateExtraLargeRingImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color return template case .ExtraLargeSimpleImage: let template = CLKComplicationTemplateExtraLargeSimpleImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil @@ -449,7 +449,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .ExtraLargeStackImage: let template = CLKComplicationTemplateExtraLargeStackImage() - if let iconProvider = iconProvider { + if let iconProvider { template.line1ImageProvider = iconProvider } else { return nil @@ -491,7 +491,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color @@ -519,19 +519,19 @@ public class WatchComplication: Object, ImmutableMappable { return template case .ModularSmallRingImage: let template = CLKComplicationTemplateModularSmallRingImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color return template case .ModularSmallSimpleImage: let template = CLKComplicationTemplateModularSmallSimpleImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil @@ -539,7 +539,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .ModularSmallStackImage: let template = CLKComplicationTemplateModularSmallStackImage() - if let iconProvider = iconProvider { + if let iconProvider { template.line1ImageProvider = iconProvider } else { return nil @@ -581,7 +581,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color @@ -693,7 +693,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .UtilitarianSmallFlat: let template = CLKComplicationTemplateUtilitarianSmallFlat() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { // optional @@ -706,12 +706,12 @@ public class WatchComplication: Object, ImmutableMappable { return template case .UtilitarianSmallRingImage: let template = CLKComplicationTemplateUtilitarianSmallRingImage() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color @@ -723,14 +723,14 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - let ringData = self.ringData + let ringData = ringData template.fillFraction = ringData.fraction template.ringStyle = ringData.style template.tintColor = ringData.color return template case .UtilitarianSmallSquare: let template = CLKComplicationTemplateUtilitarianSmallSquare() - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { return nil @@ -743,7 +743,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - if let iconProvider = iconProvider { + if let iconProvider { template.imageProvider = iconProvider } else { // optional @@ -764,7 +764,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -782,7 +782,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .GraphicCornerGaugeText: let template = CLKComplicationTemplateGraphicCornerGaugeText() - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -844,7 +844,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -857,7 +857,7 @@ public class WatchComplication: Object, ImmutableMappable { } else { return nil } - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -870,7 +870,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .GraphicCircularClosedGaugeText: let template = CLKComplicationTemplateGraphicCircularClosedGaugeText() - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -883,7 +883,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .GraphicCircularOpenGaugeSimpleText: let template = CLKComplicationTemplateGraphicCircularOpenGaugeSimpleText() - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -901,7 +901,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .GraphicCircularOpenGaugeRangeText: let template = CLKComplicationTemplateGraphicCircularOpenGaugeRangeText() - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil @@ -957,7 +957,7 @@ public class WatchComplication: Object, ImmutableMappable { return template case .GraphicRectangularTextGauge: let template = CLKComplicationTemplateGraphicRectangularTextGauge() - if let gaugeProvider = gaugeProvider { + if let gaugeProvider { template.gaugeProvider = gaugeProvider } else { return nil diff --git a/Sources/Shared/API/Models/WebhookUpdateLocation.swift b/Sources/Shared/API/Models/WebhookUpdateLocation.swift index 3b272f46e..5a73032f2 100644 --- a/Sources/Shared/API/Models/WebhookUpdateLocation.swift +++ b/Sources/Shared/API/Models/WebhookUpdateLocation.swift @@ -46,7 +46,7 @@ public struct WebhookUpdateLocation: ImmutableMappable { useLocation = true } - if let location = location, useLocation { + if let location, useLocation { self.location = location.coordinate if location.speed > -1 { @@ -64,7 +64,7 @@ public struct WebhookUpdateLocation: ImmutableMappable { if location.horizontalAccuracy > -1 { self.horizontalAccuracy = location.horizontalAccuracy } - } else if let zone = zone { + } else if let zone { if trigger != .BeaconRegionExit { self.location = zone.center self.horizontalAccuracy = zone.Radius diff --git a/Sources/Shared/API/Responses/MobileAppConfig.swift b/Sources/Shared/API/Responses/MobileAppConfig.swift index e0f1f70c8..0fce05f8d 100644 --- a/Sources/Shared/API/Responses/MobileAppConfig.swift +++ b/Sources/Shared/API/Responses/MobileAppConfig.swift @@ -41,7 +41,7 @@ public struct MobileAppConfigPushCategory: ImmutableMappable, UpdatableModelSour public init(map: Map) throws { self.title = try map.value("title", default: "Missing title") // we fall back to 'action' for android-style dynamic actions - self.identifier = try map.value("identifier", default: try map.value("action", default: "missing")) + self.identifier = try map.value("identifier", default: map.value("action", default: "missing")) self.authenticationRequired = try map.value("authenticationRequired", default: false) self.behavior = try map.value("behavior", default: "default") self.activationMode = try map.value("activationMode", default: "background") @@ -81,7 +81,7 @@ public struct MobileAppConfigPushCategory: ImmutableMappable, UpdatableModelSour public struct MobileAppConfigPush: ImmutableMappable { public var categories: [MobileAppConfigPushCategory] - internal init(categories: [MobileAppConfigPushCategory] = []) { + init(categories: [MobileAppConfigPushCategory] = []) { self.categories = [] } @@ -94,7 +94,7 @@ public struct MobileAppConfig: ImmutableMappable { public var push: MobileAppConfigPush public var actions: [MobileAppConfigAction] - internal init(push: MobileAppConfigPush = .init(), actions: [MobileAppConfigAction] = []) { + init(push: MobileAppConfigPush = .init(), actions: [MobileAppConfigAction] = []) { self.push = push self.actions = actions } diff --git a/Sources/Shared/API/Server+Fakes.swift b/Sources/Shared/API/Server+Fakes.swift index 72bc21b30..6d993fd27 100644 --- a/Sources/Shared/API/Server+Fakes.swift +++ b/Sources/Shared/API/Server+Fakes.swift @@ -1,6 +1,6 @@ import Foundation -internal extension ServerInfo { +extension ServerInfo { static func fake() -> ServerInfo { var value = ServerInfo( name: "Fake Server", @@ -34,7 +34,7 @@ internal extension ServerInfo { } } -internal extension Server { +extension Server { static func fake( identifier: Identifier = .init(rawValue: UUID().uuidString), initial: ServerInfo = .fake(), @@ -46,7 +46,7 @@ internal extension Server { } } -internal class FakeServerManager: ServerManager { +class FakeServerManager: ServerManager { var all = [Server]() var observers = [WeakWrapper]() diff --git a/Sources/Shared/API/Server.swift b/Sources/Shared/API/Server.swift index 7d1e9c4cd..1f55f9c51 100644 --- a/Sources/Shared/API/Server.swift +++ b/Sources/Shared/API/Server.swift @@ -177,7 +177,7 @@ public final class Server: Hashable, Comparable, CustomStringConvertible { let oldValue = getter() let didUpdate = setter(newValue) if newValue != oldValue, didUpdate { - observers.values.forEach { observer in + for observer in observers.values { DispatchQueue.main.async { observer(newValue) } diff --git a/Sources/Shared/API/ServerManager.swift b/Sources/Shared/API/ServerManager.swift index daac83252..807f07faa 100644 --- a/Sources/Shared/API/ServerManager.swift +++ b/Sources/Shared/API/ServerManager.swift @@ -31,7 +31,7 @@ public extension ServerManager { } func server(forServerIdentifier rawIdentifier: String?) -> Server? { - if let rawIdentifier = rawIdentifier { + if let rawIdentifier { return server(for: .init(rawValue: rawIdentifier)) } else { return nil @@ -82,7 +82,7 @@ public extension ServerManager { } } -internal protocol ServerManagerKeychain { +protocol ServerManagerKeychain { func removeAll() throws func allKeys() -> [String] func getData(_ key: String) throws -> Data? @@ -148,7 +148,7 @@ extension Keychain: ServerManagerKeychain { } } -internal final class ServerManagerImpl: ServerManager { +final class ServerManagerImpl: ServerManager { private var keychain: ServerManagerKeychain private var historicKeychain: ServerManagerKeychain private var encoder: JSONEncoder @@ -373,11 +373,11 @@ internal final class ServerManagerImpl: ServerManager { let versionString = userDefaults.string(forKey: "version") ?? "2021.1" let name = userDefaults.string(forKey: "location_name") ?? ServerInfo.defaultName - var serverInfo = ServerInfo( + var serverInfo = try ServerInfo( name: name, - connection: try decoder.decode(ConnectionInfo.self, from: connectionInfoData), - token: try decoder.decode(TokenInfo.self, from: tokenInfoData), - version: try Version(hassVersion: versionString) + connection: decoder.decode(ConnectionInfo.self, from: connectionInfoData), + token: decoder.decode(TokenInfo.self, from: tokenInfoData), + version: Version(hassVersion: versionString) ) if let name = userDefaults.string(forKey: "override_device_name") { diff --git a/Sources/Shared/API/WebSocket/HAPanel.swift b/Sources/Shared/API/WebSocket/HAPanel.swift index b2add46e4..507e4e466 100644 --- a/Sources/Shared/API/WebSocket/HAPanel.swift +++ b/Sources/Shared/API/WebSocket/HAPanel.swift @@ -85,8 +85,8 @@ public struct HAPanels: HADataDecodable, Codable, Equatable { throw HADataError.missingKey("root") } - self.init( - panelsByPath: try dictionary + try self.init( + panelsByPath: dictionary .compactMapKeys { if $0.hasPrefix("_") { return nil diff --git a/Sources/Shared/API/WebSocket/WebSocketMessage.swift b/Sources/Shared/API/WebSocket/WebSocketMessage.swift index bd14bbf32..0c2cef987 100644 --- a/Sources/Shared/API/WebSocket/WebSocketMessage.swift +++ b/Sources/Shared/API/WebSocket/WebSocketMessage.swift @@ -71,16 +71,16 @@ public class WebSocketMessage: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(MessageType, forKey: .MessageType) - if let ID = ID { + if let ID { try container.encode(ID, forKey: .ID) } - if let Success = Success { + if let Success { try container.encode(Success, forKey: .Success) } - if let Message = Message { + if let Message { try container.encode(Message, forKey: .Message) } - if let Result = Result { + if let Result { try container.encode(Result, forKey: .Result) } if let Payload { diff --git a/Sources/Shared/API/Webhook/Networking/Promise+WebhookJson.swift b/Sources/Shared/API/Webhook/Networking/Promise+WebhookJson.swift index 53fffbd46..35f1740b4 100644 --- a/Sources/Shared/API/Webhook/Networking/Promise+WebhookJson.swift +++ b/Sources/Shared/API/Webhook/Networking/Promise+WebhookJson.swift @@ -58,7 +58,7 @@ extension Promise where T == Data { secretGetter: @escaping () -> [UInt8]?, options: JSONSerialization.ReadingOptions = [.allowFragments] ) -> Promise { - if let statusCode = statusCode { + if let statusCode { switch statusCode { case 204, 205: return .value(()) diff --git a/Sources/Shared/API/Webhook/Networking/WebhookManager.swift b/Sources/Shared/API/Webhook/Networking/WebhookManager.swift index 0ac9cf992..94b1fbdd2 100644 --- a/Sources/Shared/API/Webhook/Networking/WebhookManager.swift +++ b/Sources/Shared/API/Webhook/Networking/WebhookManager.swift @@ -3,7 +3,7 @@ import ObjectMapper import PromiseKit import UserNotifications -internal enum WebhookError: LocalizedError, Equatable, CancellableError { +enum WebhookError: LocalizedError, Equatable, CancellableError { case unregisteredIdentifier(handler: String) case unexpectedType(given: String, desire: String) case unacceptableStatusCode(Int) @@ -48,12 +48,12 @@ public class WebhookManager: NSObject { "non-background" } - internal var sessionInfos = Set() - internal var currentBackgroundSessionInfo: WebhookSessionInfo { + var sessionInfos = Set() + var currentBackgroundSessionInfo: WebhookSessionInfo { sessionInfo(forIdentifier: Self.currentURLSessionIdentifier) } - internal var currentRegularSessionInfo: WebhookSessionInfo { + var currentRegularSessionInfo: WebhookSessionInfo { sessionInfo(forIdentifier: Self.currentRegularURLSessionIdentifier) } @@ -83,11 +83,11 @@ public class WebhookManager: NSObject { private var responseHandlers = [WebhookResponseIdentifier: WebhookResponseHandler.Type]() - internal var serverCache = [Identifier: Server]() + var serverCache = [Identifier: Server]() // MARK: - Lifecycle - override internal init() { + override init() { let specificKey = DispatchSpecificKey() let underlyingQueue = DispatchQueue(label: "webhookmanager-data") underlyingQueue.setSpecific(key: specificKey, value: true) @@ -109,7 +109,7 @@ public class WebhookManager: NSObject { register(responseHandler: WebhookResponseUnhandled.self, for: .unhandled) } - internal func register( + func register( responseHandler: WebhookResponseHandler.Type, for identifier: WebhookResponseIdentifier ) { @@ -227,7 +227,7 @@ public class WebhookManager: NSObject { with: urlRequest, from: data, completionHandler: { data, response, error in - if let data = data, let response = response { + if let data, let response { seal.fulfill((data, response)) } else { seal.resolve(nil, error) @@ -506,7 +506,7 @@ public class WebhookManager: NSObject { Promise { seal in let webhookURL: URL - if let baseURL = baseURL { + if let baseURL { webhookURL = baseURL.appendingPathComponent(server.info.connection.webhookPath, isDirectory: false) } else { webhookURL = server.info.connection.webhookURL() @@ -528,7 +528,7 @@ public class WebhookManager: NSObject { private func handle(result: WebhookResponseHandlerResult) { if let notification = result.notification { UNUserNotificationCenter.current().add(notification) { error in - if let error = error { + if let error { Current.Log.error("failed to add notification for result \(result): \(error)") } } @@ -592,7 +592,7 @@ extension WebhookManager: URLSessionDataDelegate, URLSessionTaskDelegate { } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - let sessionInfo = self.sessionInfo(for: session) + let sessionInfo = sessionInfo(for: session) let taskKey = TaskKey(sessionInfo: sessionInfo, task: task) let statusCode = (task.response as? HTTPURLResponse)?.statusCode @@ -684,7 +684,7 @@ extension WebhookManager: URLSessionDataDelegate, URLSessionTaskDelegate { } } -internal class WebhookSessionInfo: CustomStringConvertible, Hashable { +class WebhookSessionInfo: CustomStringConvertible, Hashable { let identifier: String let eventGroup: DispatchGroup let session: URLSession diff --git a/Sources/Shared/API/Webhook/Networking/WebhookResponseUpdateComplications.swift b/Sources/Shared/API/Webhook/Networking/WebhookResponseUpdateComplications.swift index 670436077..b9d9aa869 100644 --- a/Sources/Shared/API/Webhook/Networking/WebhookResponseUpdateComplications.swift +++ b/Sources/Shared/API/Webhook/Networking/WebhookResponseUpdateComplications.swift @@ -90,7 +90,7 @@ struct WebhookResponseUpdateComplications: WebhookResponseHandler { } #if os(watchOS) - internal static func updateComplications() { + static func updateComplications() { let server = CLKComplicationServer.sharedInstance() server.activeComplications?.forEach { diff --git a/Sources/Shared/API/Webhook/Sensors/ActivitySensor.swift b/Sources/Shared/API/Webhook/Sensors/ActivitySensor.swift index d01060e31..7f9cc8d2a 100644 --- a/Sources/Shared/API/Webhook/Sensors/ActivitySensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/ActivitySensor.swift @@ -48,7 +48,7 @@ public class ActivitySensor: SensorProvider { Current.motion.queryStartEndOnQueueHandler(start, end, queue) { activities, error in if let latestActivity = activities?.last { seal.fulfill(latestActivity) - } else if let error = error { + } else if let error { seal.reject(error) } else { seal.reject(ActivityError.noData) diff --git a/Sources/Shared/API/Webhook/Sensors/ConnectivitySensor.swift b/Sources/Shared/API/Webhook/Sensors/ConnectivitySensor.swift index 0db983ddd..5f68423a2 100644 --- a/Sources/Shared/API/Webhook/Sensors/ConnectivitySensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/ConnectivitySensor.swift @@ -123,7 +123,7 @@ public class ConnectivitySensor: SensorProvider { let networkInfo = Current.connectivity.telephonyCarriers() let radioTech = Current.connectivity.telephonyRadioAccessTechnology() - if let networkInfo = networkInfo { + if let networkInfo { return when(fulfilled: networkInfo.map { carrierSensor( carrier: $0.value, @@ -161,7 +161,7 @@ public class ConnectivitySensor: SensorProvider { "Allows VoIP": carrier.allowsVOIP, ] - if let radioTech = radioTech { + if let radioTech { sensor.Attributes?["Current Radio Technology"] = Self.getRadioTechName(radioTech) } diff --git a/Sources/Shared/API/Webhook/Sensors/GeocoderSensor.swift b/Sources/Shared/API/Webhook/Sensors/GeocoderSensor.swift index 4e34a1081..7a7c0a8f3 100644 --- a/Sources/Shared/API/Webhook/Sensors/GeocoderSensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/GeocoderSensor.swift @@ -8,7 +8,7 @@ public class GeocoderSensor: SensorProvider { case noLocation } - internal enum UserDefaultsKeys: String { + enum UserDefaultsKeys: String { case geocodeUseZone = "geocoded_location_use_zone" var title: String { @@ -55,7 +55,7 @@ public class GeocoderSensor: SensorProvider { .map { CNPostalAddressFormatter.string(from: $0, style: .mailingAddress) } .first(where: { $0.isEmpty == false }) - if let address = address { + if let address { sensor.State = address } diff --git a/Sources/Shared/API/Webhook/Sensors/InputOutputDeviceSensor.swift b/Sources/Shared/API/Webhook/Sensors/InputOutputDeviceSensor.swift index 4830af489..671d343b2 100644 --- a/Sources/Shared/API/Webhook/Sensors/InputOutputDeviceSensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/InputOutputDeviceSensor.swift @@ -49,7 +49,7 @@ private class InputOutputDeviceUpdateSignaler: SensorProviderUpdateSignaler { #endif } - private func addObserver(object: ObservedObjectType, property: PropertyType) { + private func addObserver(object: ObservedObjectType, property: some HACoreBlahProperty) { guard !observedObjects.contains(object) else { return } let observedStatus = property.addListener(objectID: object.id) { [weak self] in @@ -64,17 +64,17 @@ private class InputOutputDeviceUpdateSignaler: SensorProviderUpdateSignaler { // object IDs both alias to UInt32 so we can't rely on the type system to know which method to call #if targetEnvironment(macCatalyst) - func addCoreAudioObserver( + func addCoreAudioObserver( for id: AudioObjectID, - property: HACoreAudioProperty + property: HACoreAudioProperty ) { addObserver(object: .coreAudio(id), property: property) } #if canImport(CoreMediaIO) - func addCoreMediaObserver( + func addCoreMediaObserver( for id: CMIOObjectID, - property: HACoreMediaProperty + property: HACoreMediaProperty ) { addObserver(object: .coreMedia(id), property: property) } diff --git a/Sources/Shared/API/Webhook/Sensors/PedometerSensor.swift b/Sources/Shared/API/Webhook/Sensors/PedometerSensor.swift index 77b36e4a9..e7f3e1d5c 100644 --- a/Sources/Shared/API/Webhook/Sensors/PedometerSensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/PedometerSensor.swift @@ -46,9 +46,9 @@ public class PedometerSensor: SensorProvider { let end = Current.date() let start = Current.calendar().startOfDay(for: end) Current.pedometer.queryStartEndHandler(start, end) { data, error in - if let data = data { + if let data { seal.fulfill(data) - } else if let error = error { + } else if let error { seal.reject(error) } else { seal.reject(PedometerError.noData) diff --git a/Sources/Shared/API/Webhook/Sensors/SensorContainer.swift b/Sources/Shared/API/Webhook/Sensors/SensorContainer.swift index 4d2161ea5..203065d9f 100644 --- a/Sources/Shared/API/Webhook/Sensors/SensorContainer.swift +++ b/Sources/Shared/API/Webhook/Sensors/SensorContainer.swift @@ -8,7 +8,7 @@ public struct SensorObserverUpdate { public let sensors: Guarantee<[WebhookSensor]> public let on: Date - internal init(sensors: Guarantee<[WebhookSensor]>) { + init(sensors: Guarantee<[WebhookSensor]>) { self.sensors = sensors self.on = Current.date() } @@ -58,7 +58,7 @@ public class SensorContainer { public func register(observer: SensorObserver) { observers.add(observer) - if let lastUpdate = lastUpdate { + if let lastUpdate { observer.sensorContainer(self, didUpdate: lastUpdate) } } @@ -103,7 +103,7 @@ public class SensorContainer { private var lastUpdate: SensorObserverUpdate? { didSet { - guard let lastUpdate = lastUpdate else { return } + guard let lastUpdate else { return } observers .allObjects .compactMap { $0 as? SensorObserver } @@ -137,7 +137,7 @@ public class SensorContainer { private var lastSentSensors: HAProtected = .init(value: .init()) - internal func sensors( + func sensors( reason: SensorProviderRequest.Reason, limitedTo: [SensorProvider.Type]? = nil, location: CLLocation? = nil, @@ -153,7 +153,7 @@ public class SensorContainer { let generatedSensors = firstly { let promises = providers .filter { providerType in - if let limitedTo = limitedTo { + if let limitedTo { return limitedTo.contains(where: { ObjectIdentifier($0) == ObjectIdentifier(providerType) }) } else { return true @@ -191,8 +191,8 @@ public class SensorContainer { lastSentSensors.combine(with: new, ignoringExisting: ignoringExisting) return lastSentSensors.sensors }.sorted(by: { [weak self] lhs, rhs in - guard let self = self else { return true } - switch (self.isEnabled(sensor: lhs), self.isEnabled(sensor: rhs)) { + guard let self else { return true } + switch (isEnabled(sensor: lhs), isEnabled(sensor: rhs)) { case (true, true): return lhs < rhs case (false, false): return lhs < rhs case (true, false): return true @@ -202,9 +202,9 @@ public class SensorContainer { }) return generatedSensors.mapValues { [weak self] sensor -> WebhookSensor in - guard let self = self else { return sensor } + guard let self else { return sensor } - if self.isAllowedToSend(sensor: sensor, for: server) { + if isAllowedToSend(sensor: sensor, for: server) { return sensor } else { return WebhookSensor(redacting: sensor) diff --git a/Sources/Shared/API/Webhook/Sensors/SensorProvider.swift b/Sources/Shared/API/Webhook/Sensors/SensorProvider.swift index 6e4ef98b2..08ba65f27 100644 --- a/Sources/Shared/API/Webhook/Sensors/SensorProvider.swift +++ b/Sources/Shared/API/Webhook/Sensors/SensorProvider.swift @@ -26,7 +26,7 @@ public struct SensorProviderRequest { self.serverVersion = serverVersion } - internal var lastUpdateReason: String { + var lastUpdateReason: String { switch reason { case .registration: return "registration" diff --git a/Sources/Shared/API/Webhook/Sensors/SensorProviderDependencies.swift b/Sources/Shared/API/Webhook/Sensors/SensorProviderDependencies.swift index 5b038007f..fbfc79c2b 100644 --- a/Sources/Shared/API/Webhook/Sensors/SensorProviderDependencies.swift +++ b/Sources/Shared/API/Webhook/Sensors/SensorProviderDependencies.swift @@ -5,17 +5,17 @@ public protocol SensorProviderUpdateSignaler: AnyObject { } public class SensorProviderDependencies { - internal var updateSignalHandler: (SensorProvider.Type) -> Void = { _ in } + var updateSignalHandler: (SensorProvider.Type) -> Void = { _ in } private var updateSignalers: [String: [SensorProviderUpdateSignaler]] = [:] private func key(for sensorProvider: SensorProvider) -> String { String(describing: type(of: sensorProvider)) } - internal func existingSignaler( + func existingSignaler( for sensorProvider: SensorProvider ) -> SignalerType? { - let key = self.key(for: sensorProvider) + let key = key(for: sensorProvider) return updateSignalers[key]?.compactMap({ $0 as? SignalerType }).first } diff --git a/Sources/Shared/API/Webhook/Sensors/StorageSensor.swift b/Sources/Shared/API/Webhook/Sensors/StorageSensor.swift index a62fbbfe1..d4359b3ec 100644 --- a/Sources/Shared/API/Webhook/Sensors/StorageSensor.swift +++ b/Sources/Shared/API/Webhook/Sensors/StorageSensor.swift @@ -28,7 +28,7 @@ public class StorageSensor: SensorProvider { throw StorageError.noData } }.map { (volumes: [URLResourceKey: Int64]) -> [WebhookSensor] in - [try Self.sensor(for: volumes)] + try [Self.sensor(for: volumes)] } } diff --git a/Sources/Shared/ClientEvents/Model/ClientEventStore.swift b/Sources/Shared/ClientEvents/Model/ClientEventStore.swift index 831539c15..048ea97ab 100644 --- a/Sources/Shared/ClientEvents/Model/ClientEventStore.swift +++ b/Sources/Shared/ClientEvents/Model/ClientEventStore.swift @@ -14,7 +14,7 @@ public struct ClientEventStore { public func getEvents(filter: String? = nil) -> AnyRealmCollection { let realm = Current.realm() let objects = realm.objects(ClientEvent.self).sorted(byKeyPath: "date", ascending: false) - if let filter = filter, filter.isEmpty == false { + if let filter, filter.isEmpty == false { return AnyRealmCollection(objects.filter(NSPredicate(format: "text contains[c] %@", filter))) } else { return AnyRealmCollection(objects) diff --git a/Sources/Shared/Common/BackgroundTask.swift b/Sources/Shared/Common/BackgroundTask.swift index 097da66c0..56e0997e5 100644 --- a/Sources/Shared/Common/BackgroundTask.swift +++ b/Sources/Shared/Common/BackgroundTask.swift @@ -24,7 +24,7 @@ public enum HomeAssistantBackgroundTask { wrapping: (TimeInterval?) -> Promise ) -> Promise { func describe(_ identifier: IdentifierType?) -> String { - if let identifier = identifier { + if let identifier { #if os(iOS) if let identifier = identifier as? UIBackgroundTaskIdentifier { return String(describing: identifier.rawValue) diff --git a/Sources/Shared/Common/DiskCache.swift b/Sources/Shared/Common/DiskCache.swift index b76d1993f..a2b05b9ad 100644 --- a/Sources/Shared/Common/DiskCache.swift +++ b/Sources/Shared/Common/DiskCache.swift @@ -47,7 +47,7 @@ public final class DiskCacheImpl: DiskCache { return promise } - public func set(_ value: T, for key: String) -> Promise { + public func set(_ value: some Codable, for key: String) -> Promise { let data: Data do { diff --git a/Sources/Shared/Common/Extensions/Dictionary+Additions.swift b/Sources/Shared/Common/Extensions/Dictionary+Additions.swift index e8e563ae4..94976826c 100644 --- a/Sources/Shared/Common/Extensions/Dictionary+Additions.swift +++ b/Sources/Shared/Common/Extensions/Dictionary+Additions.swift @@ -3,7 +3,7 @@ import Foundation public extension Dictionary { func mapKeys(_ transform: (Key) throws -> T) rethrows -> [T: Value] { try reduce(into: [T: Value]()) { result, element in - result[try transform(element.key)] = element.value + try result[transform(element.key)] = element.value } } diff --git a/Sources/Shared/Common/Extensions/KeyedDecodingContainer+JSON.swift b/Sources/Shared/Common/Extensions/KeyedDecodingContainer+JSON.swift index a04e8a27c..7bb65b572 100644 --- a/Sources/Shared/Common/Extensions/KeyedDecodingContainer+JSON.swift +++ b/Sources/Shared/Common/Extensions/KeyedDecodingContainer+JSON.swift @@ -74,14 +74,14 @@ public extension UnkeyedDecodingContainer { } mutating func decode(_ type: [String: Any].Type) throws -> [String: Any] { - let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self) + let nestedContainer = try nestedContainer(keyedBy: JSONCodingKeys.self) return try nestedContainer.decode(type) } } public extension KeyedEncodingContainerProtocol where Key == JSONCodingKeys { mutating func encode(_ value: [String: Any]) throws { - try value.forEach({ key, value in + for (key, value) in value { let key = JSONCodingKeys(stringValue: key) switch value { case let value as Bool: @@ -105,7 +105,7 @@ public extension KeyedEncodingContainerProtocol where Key == JSONCodingKeys { let err = EncodingError.Context(codingPath: codingPath + [key], debugDescription: "Invalid JSON value") throw EncodingError.invalidValue(value, err) } - }) + } } } @@ -127,7 +127,7 @@ public extension KeyedEncodingContainerProtocol { public extension UnkeyedEncodingContainer { mutating func encode(_ value: [Any]) throws { - try value.enumerated().forEach({ index, value in + for (index, value) in value.enumerated() { switch value { case let value as Bool: try encode(value) @@ -151,11 +151,11 @@ public extension UnkeyedEncodingContainer { let err = EncodingError.Context(codingPath: codingPath + keys, debugDescription: "Invalid JSON value") throw EncodingError.invalidValue(value, err) } - }) + } } mutating func encode(_ value: [String: Any]) throws { - var nestedContainer = self.nestedContainer(keyedBy: JSONCodingKeys.self) + var nestedContainer = nestedContainer(keyedBy: JSONCodingKeys.self) try nestedContainer.encode(value) } } diff --git a/Sources/Shared/Common/Extensions/NSItemProvider+Additions.swift b/Sources/Shared/Common/Extensions/NSItemProvider+Additions.swift index 0de42e75f..eda0d2336 100644 --- a/Sources/Shared/Common/Extensions/NSItemProvider+Additions.swift +++ b/Sources/Shared/Common/Extensions/NSItemProvider+Additions.swift @@ -3,8 +3,8 @@ import Foundation import PromiseKit public struct ItemProviderRequest { - internal let utType: String - internal init(_ utType: CFString) { + let utType: String + init(_ utType: CFString) { self.utType = utType as String } diff --git a/Sources/Shared/Common/Extensions/Realm+Initialization.swift b/Sources/Shared/Common/Extensions/Realm+Initialization.swift index aaa8fa4fb..8a7a43c2a 100644 --- a/Sources/Shared/Common/Extensions/Realm+Initialization.swift +++ b/Sources/Shared/Common/Extensions/Realm+Initialization.swift @@ -105,7 +105,7 @@ public extension Realm { // but it seems like some time in the past, it allowed the same identifier to be inserted >1 time var discoveredIdentifiers = Set() migration.enumerateObjects(ofType: NotificationCategory.className()) { _, newObject in - if let newObject = newObject, let identifier = newObject["Identifier"] as? String { + if let newObject, let identifier = newObject["Identifier"] as? String { if discoveredIdentifiers.contains(identifier) { migration.delete(newObject) } else { @@ -155,7 +155,7 @@ public extension Realm { if oldVersion < 18 { // set the serverIdentifier to the historic value for anything synced earlier - func migrate(_ modelType: T.Type) { + func migrate(_ modelType: (some Object & UpdatableModel).Type) { migration.enumerateObjects(ofType: modelType.className()) { _, newObject in newObject?[modelType.serverIdentifierKey()] = Server.historicId.rawValue } @@ -339,12 +339,12 @@ public extension Realm { if isInWriteTransaction { promise = Promise { seal in - seal.fulfill(try block()) + try seal.fulfill(block()) } } else { promise = Current.backgroundTask(withName: "realm-write") { _ in Promise { seal in - seal.fulfill(try write(withoutNotifying: tokens, block)) + try seal.fulfill(write(withoutNotifying: tokens, block)) } } } diff --git a/Sources/Shared/Common/Extensions/UIImage+Icons.swift b/Sources/Shared/Common/Extensions/UIImage+Icons.swift index c4e37caa2..f3995d097 100644 --- a/Sources/Shared/Common/Extensions/UIImage+Icons.swift +++ b/Sources/Shared/Common/Extensions/UIImage+Icons.swift @@ -19,7 +19,7 @@ public extension UIImage { public extension MaterialDesignIcons { convenience init(serversideValueNamed value: String, fallback: MaterialDesignIcons? = nil) { - if let fallback = fallback { + if let fallback { self.init(named: value.normalizingIconString, fallback: fallback) } else { self.init(named: value.normalizingIconString) diff --git a/Sources/Shared/Common/Extensions/UIView+StackView.swift b/Sources/Shared/Common/Extensions/UIView+StackView.swift index 76bcff146..d76923541 100644 --- a/Sources/Shared/Common/Extensions/UIView+StackView.swift +++ b/Sources/Shared/Common/Extensions/UIView+StackView.swift @@ -1,4 +1,5 @@ import UIKit + #if os(iOS) public extension UIView { @@ -23,7 +24,7 @@ public extension UIView { required init?(coder: NSCoder) { fatalError() } override func didMoveToSuperview() { super.didMoveToSuperview() - if let superview = superview, superview.layoutGuides.contains(laterGuide) { + if let superview, superview.layoutGuides.contains(laterGuide) { heightAnchor.constraint(equalTo: laterGuide.heightAnchor).isActive = true } } diff --git a/Sources/Shared/Common/Extensions/URL+Extensions.swift b/Sources/Shared/Common/Extensions/URL+Extensions.swift index d4eab8c67..f81bee523 100644 --- a/Sources/Shared/Common/Extensions/URL+Extensions.swift +++ b/Sources/Shared/Common/Extensions/URL+Extensions.swift @@ -12,7 +12,7 @@ extension URL { // port will be removed if 80 or 443 by WKWebView, so we provide defaults for comparison var portWithFallback: Int? { - if let port = port { + if let port { return port } diff --git a/Sources/Shared/Common/Extensions/Version+HA.swift b/Sources/Shared/Common/Extensions/Version+HA.swift index fc8f7792f..7e216f7c5 100644 --- a/Sources/Shared/Common/Extensions/Version+HA.swift +++ b/Sources/Shared/Common/Extensions/Version+HA.swift @@ -3,9 +3,9 @@ import Version public extension Version { private static func replacements() throws -> [(regex: NSRegularExpression, replacement: String)] { - [ - (regex: try NSRegularExpression(pattern: #"\.([a-zA-Z])"#, options: []), replacement: #"-$1"#), - (regex: try NSRegularExpression(pattern: #"([0-9])([a-zA-Z])"#, options: []), replacement: #"$1-$2"#), + try [ + (regex: NSRegularExpression(pattern: #"\.([a-zA-Z])"#, options: []), replacement: #"-$1"#), + (regex: NSRegularExpression(pattern: #"([0-9])([a-zA-Z])"#, options: []), replacement: #"$1-$2"#), ] } diff --git a/Sources/Shared/Common/ObjectMapperTransformers.swift b/Sources/Shared/Common/ObjectMapperTransformers.swift index 99066a136..0390424a9 100644 --- a/Sources/Shared/Common/ObjectMapperTransformers.swift +++ b/Sources/Shared/Common/ObjectMapperTransformers.swift @@ -75,7 +75,7 @@ open class FloatToIntTransform: TransformType { } open func transformToJSON(_ value: Float?) -> Int? { - guard let value = value else { return nil } + guard let value else { return nil } return Int(value * 100) } } @@ -94,7 +94,7 @@ open class CLLocationCoordinate2DTransform: TransformType { } open func transformToJSON(_ value: CLLocationCoordinate2D?) -> [Double]? { - guard let value = value else { return nil } + guard let value else { return nil } return value.toArray() } } @@ -110,7 +110,7 @@ open class TimeIntervalToString: TransformType { } open func transformToJSON(_ value: TimeInterval?) -> String? { - guard let value = value else { return nil } + guard let value else { return nil } let interval = Int(value) let seconds = interval % 60 let minutes = (interval / 60) % 60 diff --git a/Sources/Shared/Common/SiriIntents+ConvenienceInits.swift b/Sources/Shared/Common/SiriIntents+ConvenienceInits.swift index 8df871999..7b22688df 100644 --- a/Sources/Shared/Common/SiriIntents+ConvenienceInits.swift +++ b/Sources/Shared/Common/SiriIntents+ConvenienceInits.swift @@ -16,7 +16,7 @@ public extension CallServiceIntent { self.init() self.service = "\(domain).\(service)" - if let payload = payload, let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: []), + if let payload, let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: []), let jsonString = String(data: jsonData, encoding: .utf8) { self.payload = jsonString } @@ -34,7 +34,7 @@ public extension FireEventIntent { self.init() self.eventName = eventName - if let payload = payload, let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: []), + if let payload, let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: []), let jsonString = String(data: jsonData, encoding: .utf8) { self.eventData = jsonString } @@ -105,7 +105,7 @@ public extension IntentAction { } func asAction() -> Action? { - guard let identifier = identifier, identifier.isEmpty == false else { + guard let identifier, identifier.isEmpty == false else { return nil } diff --git a/Sources/Shared/Common/WatchBackgroundRefreshScheduler.swift b/Sources/Shared/Common/WatchBackgroundRefreshScheduler.swift index 13628aea7..a43af3c65 100644 --- a/Sources/Shared/Common/WatchBackgroundRefreshScheduler.swift +++ b/Sources/Shared/Common/WatchBackgroundRefreshScheduler.swift @@ -26,7 +26,7 @@ public class WatchBackgroundRefreshScheduler { #endif } - internal func nextFireDate() -> Date { + func nextFireDate() -> Date { // Apple documents that, if we have an active complication, we can reliably refresh 4 times per hour // so we divide this into 0 / 15 / 30 / 45 let possibleComponents = stride(from: 0, to: 60, by: 15).map { minute in diff --git a/Sources/Shared/Environment/ActiveStateManager.swift b/Sources/Shared/Environment/ActiveStateManager.swift index 1fc9ebfc7..adb22c5a8 100644 --- a/Sources/Shared/Environment/ActiveStateManager.swift +++ b/Sources/Shared/Environment/ActiveStateManager.swift @@ -69,7 +69,7 @@ public class ActiveStateManager { setup() } - internal var idleTimer: Timer? { + var idleTimer: Timer? { willSet { Current.Log.info(newValue == nil ? "removing timer" : "starting timer") idleTimer?.invalidate() @@ -280,7 +280,7 @@ private enum UpdateType: CaseIterable { } }) - if let found = found { + if let found { self = found } else { return nil diff --git a/Sources/Shared/Environment/Constants.swift b/Sources/Shared/Environment/Constants.swift index 9e5c2a2cb..0daa5e130 100644 --- a/Sources/Shared/Environment/Constants.swift +++ b/Sources/Shared/Environment/Constants.swift @@ -126,7 +126,7 @@ public enum Constants { SharedPlistFiles.Info.cfBundleShortVersionString } - internal static var clientVersion: Version { + static var clientVersion: Version { // swiftlint:disable:next force_try var clientVersion = try! Version(version) clientVersion.build = build diff --git a/Sources/Shared/Environment/CrashReporter.swift b/Sources/Shared/Environment/CrashReporter.swift index 4c92eed66..85919e252 100644 --- a/Sources/Shared/Environment/CrashReporter.swift +++ b/Sources/Shared/Environment/CrashReporter.swift @@ -13,7 +13,7 @@ public class CrashReporterImpl: CrashReporter { public var hasCrashReporter: Bool = false public var hasAnalytics: Bool = false - internal func setup() { + func setup() { guard Current.settingsStore.privacy.crashes else { return } diff --git a/Sources/Shared/Environment/DeviceBattery.swift b/Sources/Shared/Environment/DeviceBattery.swift index 992d661a7..be10ae750 100644 --- a/Sources/Shared/Environment/DeviceBattery.swift +++ b/Sources/Shared/Environment/DeviceBattery.swift @@ -89,7 +89,7 @@ public struct DeviceBattery { } if let serialNumber = info[kIOPSHardwareSerialNumberKey] as? String { self.uniqueID = serialNumber - } else if let name = name { + } else if let name { self.uniqueID = name } else if let type = info[kIOPSTypeKey] as? String { self.uniqueID = type diff --git a/Sources/Shared/Environment/DeviceWrapper.swift b/Sources/Shared/Environment/DeviceWrapper.swift index 5a303d0b5..6465508ae 100644 --- a/Sources/Shared/Environment/DeviceWrapper.swift +++ b/Sources/Shared/Environment/DeviceWrapper.swift @@ -150,15 +150,13 @@ public class DeviceWrapper { #if targetEnvironment(macCatalyst) let seconds = CGEventSource.secondsSinceLastEventType( .combinedSessionState, - eventType: { - /* - Apple's docs say: - > The event type to access. To get the elapsed time since the previous input event—keyboard, mouse, or - > tablet—specify kCGAnyInputEventType. - But kCGAnyInputEventType isn't available in Swift. In Objective-C it's defined as `((CGEventType)(~0))` - */ - CGEventType(rawValue: ~0)! - }() + eventType: /* + Apple's docs say: + > The event type to access. To get the elapsed time since the previous input event—keyboard, mouse, or + > tablet—specify kCGAnyInputEventType. + But kCGAnyInputEventType isn't available in Swift. In Objective-C it's defined as `((CGEventType)(~0))` + */ + CGEventType(rawValue: ~0)! ) return .init(value: seconds, unit: .seconds) #else diff --git a/Sources/Shared/Environment/DeviceWrapperBatteryObserver.swift b/Sources/Shared/Environment/DeviceWrapperBatteryObserver.swift index 7761242c8..613f2bfb8 100644 --- a/Sources/Shared/Environment/DeviceWrapperBatteryObserver.swift +++ b/Sources/Shared/Environment/DeviceWrapperBatteryObserver.swift @@ -83,7 +83,7 @@ public class DeviceWrapperBatteryNotificationCenter { private func addIOKitObserver(for notificationName: CFString) { let callback: CFNotificationCallback = { _, observer, name, /* ignored */ _, /* ignored */ _ in // this block is a C block, which cannot weakly capture self, so we do the dance - guard let observer = observer else { + guard let observer else { Current.Log.error("unexpected nil observer for battery sensor") return } diff --git a/Sources/Shared/Environment/Environment.swift b/Sources/Shared/Environment/Environment.swift index 265f6e400..3066e68c8 100644 --- a/Sources/Shared/Environment/Environment.swift +++ b/Sources/Shared/Environment/Environment.swift @@ -49,7 +49,7 @@ public var Current: AppEnvironment { /// The current "operating envrionment" the app. Implementations can be swapped out to facilitate better /// unit tests. public class AppEnvironment { - internal init() { + init() { PromiseKit.conf.logHandler = { event in Current.Log.info { switch event { @@ -74,7 +74,7 @@ public class AppEnvironment { } } - internal func setup() { + func setup() { _ = Current // just to make sure we don't crash for this case (crashReporter as? CrashReporterImpl)?.setup() diff --git a/Sources/Shared/Environment/LocalizedManager.swift b/Sources/Shared/Environment/LocalizedManager.swift index d69c6afc8..17a37c886 100644 --- a/Sources/Shared/Environment/LocalizedManager.swift +++ b/Sources/Shared/Environment/LocalizedManager.swift @@ -51,7 +51,7 @@ public class LocalizedManager { let request = StringProviderRequest(key: key, table: table, defaultValue: defaultValue) let override = stringProviders.lazy.compactMap { $0(request) }.first - if let override = override { + if let override { return override } diff --git a/Sources/Shared/Environment/ServerAlerter.swift b/Sources/Shared/Environment/ServerAlerter.swift index ab2314983..beb1415c0 100644 --- a/Sources/Shared/Environment/ServerAlerter.swift +++ b/Sources/Shared/Environment/ServerAlerter.swift @@ -39,11 +39,11 @@ public struct ServerAlert: Codable, Equatable { } public func shouldTrigger(for compare: Version) -> Bool { - if let min = min, let max = max { + if let min, let max { return compare >= min && compare <= max - } else if let min = min { + } else if let min { return compare >= min - } else if let max = max { + } else if let max { return compare <= max } else { // no provided min or max means it doesn't affect this version at all @@ -71,7 +71,7 @@ public struct ServerAlert: Codable, Equatable { self.core = try container.decodeIfPresent(VersionRequirement.self, forKey: .core) ?? .init(min: nil, max: nil) } - internal init( + init( id: String, date: Date, url: URL, @@ -103,7 +103,7 @@ public struct ServerAlert: Codable, Equatable { public class ServerAlerter { private var apiUrl: URL { URL(string: "https://alerts.home-assistant.io/mobile.json")! } - internal enum AlerterError: LocalizedError { + enum AlerterError: LocalizedError { case privacyDisabled var errorDescription: String? { @@ -130,7 +130,7 @@ public class ServerAlerter { struct FailableServerAlert: Decodable { var alert: ServerAlert? init(from decoder: Decoder) throws { - alert = try? ServerAlert(from: decoder) + self.alert = try? ServerAlert(from: decoder) } } return try with(JSONDecoder()) { diff --git a/Sources/Shared/Environment/Style.swift b/Sources/Shared/Environment/Style.swift index e9240a47c..a4188e9ea 100644 --- a/Sources/Shared/Environment/Style.swift +++ b/Sources/Shared/Environment/Style.swift @@ -19,7 +19,7 @@ public struct Style { override func didMoveToSuperview() { super.didMoveToSuperview() - if let superview = superview { + if let superview { switch traitCollection.userInterfaceIdiom { case .pad, .mac: widthAnchor.constraint(equalTo: superview.readableContentGuide.widthAnchor) diff --git a/Sources/Shared/Environment/Updater.swift b/Sources/Shared/Environment/Updater.swift index 92c05845b..d447b8474 100644 --- a/Sources/Shared/Environment/Updater.swift +++ b/Sources/Shared/Environment/Updater.swift @@ -58,7 +58,7 @@ public struct AvailableUpdate: Codable, Comparable { public class Updater { private var apiUrl: URL { URL(string: "https://api.github.com/repos/home-assistant/ios/releases?per_page=25")! } - internal enum UpdateError: LocalizedError { + enum UpdateError: LocalizedError { case unsupportedPlatform case onLatestVersion case privacyDisabled diff --git a/Sources/Shared/Iconic/MDIMigration.swift b/Sources/Shared/Iconic/MDIMigration.swift index 8500bdf86..9db994351 100644 --- a/Sources/Shared/Iconic/MDIMigration.swift +++ b/Sources/Shared/Iconic/MDIMigration.swift @@ -1,7 +1,7 @@ import Foundation // https://github.com/home-assistant/frontend/blob/92d30a889663008317f7a28faa65beea025f0bfd/src/components/ha-icon.ts -struct MDIMigration { +enum MDIMigration { // MDI Version number is based on number of icons, so count is directly related to version static let migrationNumber: Int = MaterialDesignIcons.count / 1000 - 5 diff --git a/Sources/Shared/Intents/AssistIntentHandler.swift b/Sources/Shared/Intents/AssistIntentHandler.swift index 00872c977..e3b1e73f9 100644 --- a/Sources/Shared/Intents/AssistIntentHandler.swift +++ b/Sources/Shared/Intents/AssistIntentHandler.swift @@ -82,7 +82,7 @@ class AssistIntentHandler: NSObject, AssistIntentHandling { }.done { object, original in Current.Log.info("finishing with \(object)") let value = IntentAssistResult(identifier: nil, display: object.speech) - value.json = String(decoding: try JSONSerialization.data(withJSONObject: original), as: UTF8.self) + value.json = try String(decoding: JSONSerialization.data(withJSONObject: original), as: UTF8.self) completion(.success(result: value)) }.catch { error in Current.Log.error("erroring with \(error)") diff --git a/Sources/Shared/Location/CLLocationManager+OneShotLocation.swift b/Sources/Shared/Location/CLLocationManager+OneShotLocation.swift index 1d9f242bb..642f99b17 100644 --- a/Sources/Shared/Location/CLLocationManager+OneShotLocation.swift +++ b/Sources/Shared/Location/CLLocationManager+OneShotLocation.swift @@ -47,7 +47,7 @@ enum OneShotError: Error, Equatable, LocalizedError, CustomNSError { } } -internal struct PotentialLocation: Comparable, CustomStringConvertible { +struct PotentialLocation: Comparable, CustomStringConvertible { static func desiredAccuracy(for accuracy: CLAccuracyAuthorization) -> CLLocationAccuracy { switch accuracy { case .fullAccuracy: return 100.0 @@ -165,7 +165,7 @@ internal struct PotentialLocation: Comparable, CustomStringConvertible { } } -internal final class OneShotLocationProxy: NSObject, CLLocationManagerDelegate { +final class OneShotLocationProxy: NSObject, CLLocationManagerDelegate { private(set) var promise: Promise private let seal: Resolver private let locationManager: CLLocationManager @@ -231,7 +231,7 @@ internal final class OneShotLocationProxy: NSObject, CLLocationManagerDelegate { let bestLocation = potentialLocations.sorted().last - if let bestLocation = bestLocation { + if let bestLocation { switch bestLocation.quality { case .perfect: Current.Log.info("Got a perfect location!") diff --git a/Sources/Shared/Location/LocationTrigger.swift b/Sources/Shared/Location/LocationTrigger.swift index 6bc6fb1db..f4365b296 100644 --- a/Sources/Shared/Location/LocationTrigger.swift +++ b/Sources/Shared/Location/LocationTrigger.swift @@ -30,7 +30,7 @@ public enum LocationUpdateTrigger: String, CaseIterable { case Unknown = "Unknown" public func oneShotTimeout(maximum: TimeInterval?) -> TimeInterval { - if let maximum = maximum { + if let maximum { // the system appears to have given us a reasonable baseline, leave some time for network call return max(maximum - 5.0, 1.0) } diff --git a/Sources/Shared/Notifications/LocalPush/LocalPushEvent.swift b/Sources/Shared/Notifications/LocalPush/LocalPushEvent.swift index bd8579090..87077cbf0 100644 --- a/Sources/Shared/Notifications/LocalPush/LocalPushEvent.swift +++ b/Sources/Shared/Notifications/LocalPush/LocalPushEvent.swift @@ -168,7 +168,7 @@ private struct Sound { func asSound() -> UNNotificationSound? { let defaultSound: UNNotificationSound = { if critical { - if let level = level { + if let level { return .defaultCriticalSound(withAudioVolume: level) } else { return .defaultCritical @@ -185,7 +185,7 @@ private struct Sound { return defaultSound #else if critical { - if let level = level { + if let level { return .criticalSoundNamed(name, withAudioVolume: level) } else { return .criticalSoundNamed(name) diff --git a/Sources/Shared/Notifications/LocalPush/LocalPushManager.swift b/Sources/Shared/Notifications/LocalPush/LocalPushManager.swift index a91722a60..22f3c8ba3 100644 --- a/Sources/Shared/Notifications/LocalPush/LocalPushManager.swift +++ b/Sources/Shared/Notifications/LocalPush/LocalPushManager.swift @@ -97,7 +97,7 @@ public class LocalPushManager { } public func invalidate() { - if let subscription = subscription { + if let subscription { Current.Log.info("cancelling") subscription.cancel() } else { diff --git a/Sources/Shared/Notifications/LocalPush/UserDefaultsValueSync.swift b/Sources/Shared/Notifications/LocalPush/UserDefaultsValueSync.swift index 1720eed1e..3571f064b 100644 --- a/Sources/Shared/Notifications/LocalPush/UserDefaultsValueSync.swift +++ b/Sources/Shared/Notifications/LocalPush/UserDefaultsValueSync.swift @@ -69,7 +69,7 @@ public class UserDefaultsValueSync: NSObject { change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer? ) { - guard let value = value else { return } + guard let value else { return } for observer in observers { observer.handler(value) diff --git a/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentManager.swift b/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentManager.swift index f05d98b23..7224115b1 100644 --- a/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentManager.swift +++ b/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentManager.swift @@ -53,7 +53,7 @@ class NotificationAttachmentManagerImpl: NotificationAttachmentManager { throw error } else { #if os(iOS) - return .value(try self.attachment(for: error, api: api)) + return try .value(attachment(for: error, api: api)) #else throw error #endif @@ -92,7 +92,7 @@ class NotificationAttachmentManagerImpl: NotificationAttachmentManager { throw error } else { #if os(iOS) - return .value(try self.savedImage(for: error, api: api).0) + return try .value(self.savedImage(for: error, api: api).0) #else throw error #endif @@ -161,7 +161,7 @@ class NotificationAttachmentManagerImpl: NotificationAttachmentManager { ) throws -> UNNotificationAttachment { let (url, localizedString) = try savedImage(for: error, api: api) - return with(try UNNotificationAttachment( + return try with(UNNotificationAttachment( identifier: "error", url: url, options: [ diff --git a/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentParser.swift b/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentParser.swift index 9fde20f71..8a34e125d 100644 --- a/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentParser.swift +++ b/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentParser.swift @@ -3,12 +3,12 @@ import Foundation import PromiseKit import UserNotifications -internal protocol NotificationAttachmentParser { +protocol NotificationAttachmentParser { init() func attachmentInfo(from content: UNNotificationContent) -> Guarantee } -internal enum NotificationAttachmentParserResult: Equatable { +enum NotificationAttachmentParserResult: Equatable { case fulfilled(NotificationAttachmentInfo) case missing case rejected(Error) @@ -42,7 +42,7 @@ internal enum NotificationAttachmentParserResult: Equatable { } } -internal struct NotificationAttachmentInfo: Equatable { +struct NotificationAttachmentInfo: Equatable { var url: URL var needsAuth: Bool var typeHint: CFString? @@ -52,11 +52,11 @@ internal struct NotificationAttachmentInfo: Equatable { var attachmentOptions: [String: Any] { var options = [String: Any]() - if let typeHint = typeHint { + if let typeHint { options[UNNotificationAttachmentOptionsTypeHintKey] = typeHint } - if let hideThumbnail = hideThumbnail { + if let hideThumbnail { options[UNNotificationAttachmentOptionsThumbnailHiddenKey] = hideThumbnail } diff --git a/Sources/Shared/Notifications/UNNotificationContent+Additions.swift b/Sources/Shared/Notifications/UNNotificationContent+Additions.swift index 590b1000f..cbc61231d 100644 --- a/Sources/Shared/Notifications/UNNotificationContent+Additions.swift +++ b/Sources/Shared/Notifications/UNNotificationContent+Additions.swift @@ -13,7 +13,7 @@ public extension UNNotificationContent { } static func combinedAction(base: String, appended: String) -> String { - [base, appended].joined(separator: String(Self.separator)) + [base, appended].joined(separator: String(separator)) } var userInfoActionConfigs: [MobileAppConfigPushCategory.Action] { diff --git a/Sources/Shared/Settings/SettingsStore.swift b/Sources/Shared/Settings/SettingsStore.swift index e790662fe..3bb6720dc 100644 --- a/Sources/Shared/Settings/SettingsStore.swift +++ b/Sources/Shared/Settings/SettingsStore.swift @@ -75,7 +75,7 @@ public class SettingsStore { public struct PageZoom: CaseIterable, Equatable, CustomStringConvertible { public let zoom: Int - internal init?(preference: Int) { + init?(preference: Int) { guard Self.allCases.contains(where: { $0.zoom == preference }) else { // in case one of the options causes problems, removing it from allCases will kill it Current.Log.info("disregarding zoom preference for \(preference)") @@ -85,7 +85,7 @@ public class SettingsStore { self.zoom = preference } - internal init(_ zoom: IntegerLiteralType) { + init(_ zoom: IntegerLiteralType) { self.zoom = zoom } @@ -173,7 +173,7 @@ public class SettingsStore { } } set { - if let newValue = newValue { + if let newValue { precondition(newValue > 0) prefs.set(newValue, forKey: "periodicUpdateInterval") } else { @@ -190,7 +190,7 @@ public class SettingsStore { public var updates: Bool public var updatesIncludeBetas: Bool - internal static func key(for keyPath: KeyPath) -> String { + static func key(for keyPath: KeyPath) -> String { switch keyPath { case \.messaging: return "messagingEnabled" case \.crashes: return "crashesEnabled" @@ -202,7 +202,7 @@ public class SettingsStore { } } - internal static func `default`(for keyPath: KeyPath) -> Bool { + static func `default`(for keyPath: KeyPath) -> Bool { switch keyPath { case \.messaging: return true case \.crashes: return false @@ -292,7 +292,7 @@ public class SettingsStore { server = Current.servers.all.first } - if let server = server { + if let server { return (server, prefs.string(forKey: "menuItemTemplate") ?? "") } else { return nil @@ -315,7 +315,7 @@ public class SettingsStore { public var significantLocationChange: Bool public var pushNotifications: Bool - internal static func key(for keyPath: KeyPath) -> String { + static func key(for keyPath: KeyPath) -> String { switch keyPath { case \.zone: return "locationUpdateOnZone" case \.backgroundFetch: return "locationUpdateOnBackgroundFetch" diff --git a/Sources/Vehicle/Templates/Actions/CarPlayActionsViewModel.swift b/Sources/Vehicle/Templates/Actions/CarPlayActionsViewModel.swift index da204fac9..2c590f0cb 100644 --- a/Sources/Vehicle/Templates/Actions/CarPlayActionsViewModel.swift +++ b/Sources/Vehicle/Templates/Actions/CarPlayActionsViewModel.swift @@ -51,7 +51,7 @@ final class CarPlayActionsViewModel { trigger: nil ) UNUserNotificationCenter.current().add(request) { error in - if let error = error { + if let error { Current.Log .info("Error scheduling CarPlay Introduction action notification: \(error.localizedDescription)") } diff --git a/Sources/Vehicle/Templates/Areas/CarPlayAreasViewModel.swift b/Sources/Vehicle/Templates/Areas/CarPlayAreasViewModel.swift index bcb6bee2f..11da98588 100644 --- a/Sources/Vehicle/Templates/Areas/CarPlayAreasViewModel.swift +++ b/Sources/Vehicle/Templates/Areas/CarPlayAreasViewModel.swift @@ -124,7 +124,7 @@ final class CarPlayAreasViewModel { templateProvider?.paginatedList.updateItems(items: items) } - + /// - returns: area_id : [device_id] private func mapToareasAndEntities(devicesAndAreas: [HADeviceAreaResponse]) -> [String: [String]] { devicesAndAreas.reduce(into: [:]) { partialResult, device in @@ -139,7 +139,7 @@ final class CarPlayAreasViewModel { } } } - + /// - returns: area_id : [entity_id] private func mapToAreasAndEntitiesDict(areasAndEntities: [HAEntityAreaResponse]) -> [String: [String]] { areasAndEntities.reduce(into: [:]) { partialResult, entity in @@ -153,7 +153,6 @@ final class CarPlayAreasViewModel { partialResult[areaId] = [entityId] } } - } private func listItemHandler(area: HAAreaResponse, entityIdsForAreaId: [String], server: Server) { diff --git a/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListTemplate.swift b/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListTemplate.swift index 72d293759..d0a33a3af 100644 --- a/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListTemplate.swift +++ b/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListTemplate.swift @@ -47,7 +47,7 @@ final class CarPlayEntitiesListTemplate: CarPlayTemplateProvider { } func updateItems(entityProviders: [CarPlayEntityListItem]) { - entityProviders.forEach { entityProvider in + for entityProvider in entityProviders { entityProvider.template.handler = { [weak self] _, completion in self?.viewModel.handleEntityTap(entity: entityProvider.entity, completion: completion) } diff --git a/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListViewModel.swift b/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListViewModel.swift index cb931a6aa..3dcb0359b 100644 --- a/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListViewModel.swift +++ b/Sources/Vehicle/Templates/Entities/CarPlayEntitiesListViewModel.swift @@ -99,9 +99,9 @@ final class CarPlayEntitiesListViewModel { func handleEntityTap(entity: HAEntity, completion: @escaping () -> Void) { firstly { [weak self] () -> Promise in - guard let self = self else { return .init(error: CPEntityError.unknown) } + guard let self else { return .init(error: CPEntityError.unknown) } - let api = Current.api(for: self.server) + let api = Current.api(for: server) if let domain = Domain(rawValue: entity.domain), domain == .lock { templateProvider?.displayLockConfirmation(entity: entity, completion: { diff --git a/Sources/Vehicle/Templates/Responses/HAAreaResponse.swift b/Sources/Vehicle/Templates/Responses/HAAreaResponse.swift index 1af240b82..caf972d44 100644 --- a/Sources/Vehicle/Templates/Responses/HAAreaResponse.swift +++ b/Sources/Vehicle/Templates/Responses/HAAreaResponse.swift @@ -8,15 +8,15 @@ struct HAAreaResponse: HADataDecodable { let picture: String? init(data: HAData) throws { - self.init( - aliases: try data.decode("aliases"), - areaId: try data.decode("area_id"), - name: try data.decode("name"), + try self.init( + aliases: data.decode("aliases"), + areaId: data.decode("area_id"), + name: data.decode("name"), picture: try? data.decode("picture") ) } - internal init(aliases: [String], areaId: String, name: String, picture: String? = nil) { + init(aliases: [String], areaId: String, name: String, picture: String? = nil) { self.aliases = aliases self.areaId = areaId self.name = name @@ -37,7 +37,7 @@ struct HAEntityAreaResponse: HADataDecodable { ) } - internal init(areaId: String?, entityId: String?, deviceId: String?) { + init(areaId: String?, entityId: String?, deviceId: String?) { self.areaId = areaId self.entityId = entityId self.deviceId = deviceId @@ -55,7 +55,7 @@ struct HADeviceAreaResponse: HADataDecodable { ) } - internal init(areaId: String?, deviceId: String?) { + init(areaId: String?, deviceId: String?) { self.areaId = areaId self.deviceId = deviceId } diff --git a/Tests/App/Auth/OnboardingAuth.test.swift b/Tests/App/Auth/OnboardingAuth.test.swift index 2016afae3..6dee48fbd 100644 --- a/Tests/App/Auth/OnboardingAuth.test.swift +++ b/Tests/App/Auth/OnboardingAuth.test.swift @@ -480,14 +480,14 @@ class FakeOnboardingAuthPostStepBeforeRegister: FakeOnboardingAuthPostStep { class FakeOnboardingAuthPostStepBeforeRegister1: FakeOnboardingAuthPostStepBeforeRegister, FakeAuthStepResultable { static var result: Promise = .init(error: TestError.any) { didSet { - (Self.wasInvokedPromise, Self.wasInvokedResolver) = Guarantee.pending() + (wasInvokedPromise, wasInvokedResolver) = Guarantee.pending() } } static var wasInvoked: Bool = false { didSet { if wasInvoked { - Self.wasInvokedResolver?(()) + wasInvokedResolver?(()) } } } @@ -525,14 +525,14 @@ class FakeOnboardingAuthPostStepRegister: FakeOnboardingAuthPostStep { class FakeOnboardingAuthPostStepRegister1: FakeOnboardingAuthPostStepRegister, FakeAuthStepResultable { static var result: Promise = .init(error: TestError.any) { didSet { - (Self.wasInvokedPromise, Self.wasInvokedResolver) = Guarantee.pending() + (wasInvokedPromise, wasInvokedResolver) = Guarantee.pending() } } static var wasInvoked: Bool = false { didSet { if wasInvoked { - Self.wasInvokedResolver?(()) + wasInvokedResolver?(()) } } } @@ -570,14 +570,14 @@ class FakeOnboardingAuthPostStepAfterRegister: FakeOnboardingAuthPostStep { class FakeOnboardingAuthPostStepAfterRegister1: FakeOnboardingAuthPostStepAfterRegister, FakeAuthStepResultable { static var result: Promise = .init(error: TestError.any) { didSet { - (Self.wasInvokedPromise, Self.wasInvokedResolver) = Guarantee.pending() + (wasInvokedPromise, wasInvokedResolver) = Guarantee.pending() } } static var wasInvoked: Bool = false { didSet { if wasInvoked { - Self.wasInvokedResolver?(()) + wasInvokedResolver?(()) } } } @@ -615,14 +615,14 @@ class FakeOnboardingAuthPostStepComplete: FakeOnboardingAuthPostStep { class FakeOnboardingAuthPostStepComplete1: FakeOnboardingAuthPostStepComplete, FakeAuthStepResultable { static var result: Promise = .init(error: TestError.any) { didSet { - (Self.wasInvokedPromise, Self.wasInvokedResolver) = Guarantee.pending() + (wasInvokedPromise, wasInvokedResolver) = Guarantee.pending() } } static var wasInvoked: Bool = false { didSet { if wasInvoked { - Self.wasInvokedResolver?(()) + wasInvokedResolver?(()) } } } diff --git a/Tests/App/Auth/OnboardingAuthLoginImpl.test.swift b/Tests/App/Auth/OnboardingAuthLoginImpl.test.swift index 7e14cdd4e..710adc6a5 100644 --- a/Tests/App/Auth/OnboardingAuthLoginImpl.test.swift +++ b/Tests/App/Auth/OnboardingAuthLoginImpl.test.swift @@ -17,7 +17,7 @@ class OnboardingAuthLoginImplTests: XCTestCase { login = OnboardingAuthLoginImpl() login.loginViewControllerClass = FakeOnboardingAuthLoginViewController.self - authDetails = try OnboardingAuthDetails(baseURL: try XCTUnwrap(URL(string: "http://example.com:8123"))) + authDetails = try OnboardingAuthDetails(baseURL: XCTUnwrap(URL(string: "http://example.com:8123"))) } func testCancelled() throws { @@ -36,14 +36,14 @@ class OnboardingAuthLoginImplTests: XCTestCase { func testInvalidURL() throws { let result = login.open(authDetails: authDetails, sender: sender) let viewController = try XCTUnwrap(FakeOnboardingAuthLoginViewController.lastCreated) - viewController.resolver.fulfill(try XCTUnwrap(URL(string: "homeassistant://auth-callback?no_code_here=true"))) + try viewController.resolver.fulfill(XCTUnwrap(URL(string: "homeassistant://auth-callback?no_code_here=true"))) XCTAssertThrowsError(try hang(result)) } func testSuccess() throws { let result = login.open(authDetails: authDetails, sender: sender) let viewController = try XCTUnwrap(FakeOnboardingAuthLoginViewController.lastCreated) - viewController.resolver.fulfill(try XCTUnwrap(URL(string: "homeassistant://auth-callback?code=code_123"))) + try viewController.resolver.fulfill(XCTUnwrap(URL(string: "homeassistant://auth-callback?code=code_123"))) XCTAssertEqual(try hang(result), "code_123") } } diff --git a/Tests/App/Auth/OnboardingAuthLoginViewController.test.swift b/Tests/App/Auth/OnboardingAuthLoginViewController.test.swift index aeebbd7a5..e38709ffa 100644 --- a/Tests/App/Auth/OnboardingAuthLoginViewController.test.swift +++ b/Tests/App/Auth/OnboardingAuthLoginViewController.test.swift @@ -10,7 +10,7 @@ class OnboardingAuthLoginViewControllerImplTests: XCTestCase { override func setUpWithError() throws { try super.setUpWithError() - controller = .init(authDetails: try .init(baseURL: URL(string: "https://www.example.com")!)) + controller = try .init(authDetails: .init(baseURL: URL(string: "https://www.example.com")!)) } func testError() { diff --git a/Tests/App/Auth/OnboardingAuthStepConnectivity.test.swift b/Tests/App/Auth/OnboardingAuthStepConnectivity.test.swift index ca9b09180..5686752bf 100644 --- a/Tests/App/Auth/OnboardingAuthStepConnectivity.test.swift +++ b/Tests/App/Auth/OnboardingAuthStepConnectivity.test.swift @@ -44,8 +44,8 @@ class OnboardingAuthStepConnectivityTests: XCTestCase { statusCode: Int ) { do { - client.urlProtocol(proto, didReceive: try XCTUnwrap(HTTPURLResponse( - url: try XCTUnwrap(authDetails).url, + try client.urlProtocol(proto, didReceive: XCTUnwrap(HTTPURLResponse( + url: XCTUnwrap(authDetails).url, statusCode: statusCode, httpVersion: nil, headerFields: nil @@ -135,8 +135,8 @@ class OnboardingAuthStepConnectivityTests: XCTestCase { func newSecTrust() throws -> SecTrust { var secTrust: SecTrust? - SecTrustCreateWithCertificates([ - try XCTUnwrap(SecCertificateCreateWithData(nil, certificate as CFData)), + try SecTrustCreateWithCertificates([ + XCTUnwrap(SecCertificateCreateWithData(nil, certificate as CFData)), ] as CFArray, nil, &secTrust) return try XCTUnwrap(secTrust) } @@ -371,7 +371,7 @@ class ConnectivityURLProtocol: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { true } override func startLoading() { - if let client = client { + if let client { Self.handler(self, client) } } diff --git a/Tests/App/Auth/OnboardingAuthStepDuplicate.test.swift b/Tests/App/Auth/OnboardingAuthStepDuplicate.test.swift index e62777b7f..75c8768a2 100644 --- a/Tests/App/Auth/OnboardingAuthStepDuplicate.test.swift +++ b/Tests/App/Auth/OnboardingAuthStepDuplicate.test.swift @@ -66,8 +66,8 @@ class OnboardingAuthStepDuplicateTests: XCTestCase { let result = step.perform(point: .beforeRegister) let testError = HAError.internal(debugDescription: "unit-test") - connection.pendingRequests.forEach { - $0.completion(.failure(testError)) + for pendingRequest in connection.pendingRequests { + pendingRequest.completion(.failure(testError)) } XCTAssertThrowsError(try hang(result)) { error in @@ -78,8 +78,8 @@ class OnboardingAuthStepDuplicateTests: XCTestCase { func testRequestWrongDataType() { let result = step.perform(point: .beforeRegister) - connection.pendingRequests.forEach { - $0.completion(.success(.primitive(true))) + for pendingRequest in connection.pendingRequests { + pendingRequest.completion(.success(.primitive(true))) } XCTAssertThrowsError(try hang(result)) { error in diff --git a/Tests/App/LocalizedStrings.test.swift b/Tests/App/LocalizedStrings.test.swift index d591d194a..faa66d060 100644 --- a/Tests/App/LocalizedStrings.test.swift +++ b/Tests/App/LocalizedStrings.test.swift @@ -5,9 +5,9 @@ import XCTest class LocalizedStrings: XCTestCase { func testLanguages() throws { - let expressions: [NSRegularExpression] = [ - try NSRegularExpression(pattern: "%{1,2}[+0123456789$.luq]*?[sduiefgcCp@]", options: []), - try NSRegularExpression(pattern: "\\$\\{[^}]+\\}", options: []), + let expressions: [NSRegularExpression] = try [ + NSRegularExpression(pattern: "%{1,2}[+0123456789$.luq]*?[sduiefgcCp@]", options: []), + NSRegularExpression(pattern: "\\$\\{[^}]+\\}", options: []), ] for bundle in [ @@ -41,7 +41,7 @@ class LocalizedStrings: XCTestCase { var stringsFiles = [String]() for case let url as URL in try XCTUnwrap(FileManager.default.enumerator( - at: try XCTUnwrap(bundle.resourceURL), + at: XCTUnwrap(bundle.resourceURL), includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsSubdirectoryDescendants] )) { @@ -68,7 +68,7 @@ class LocalizedStrings: XCTestCase { return try stringsFiles.map { strings in func value(for language: String) throws -> LanguageWithStrings { - try .init(url: try XCTUnwrap(bundle.url( + try .init(url: XCTUnwrap(bundle.url( forResource: strings, withExtension: "strings", subdirectory: nil, @@ -76,11 +76,11 @@ class LocalizedStrings: XCTestCase { ))) } - return LanguageSet( + return try LanguageSet( name: strings, - english: try value(for: "en"), - other: Dictionary(uniqueKeysWithValues: try languages.map { language in - (key: language, value: try value(for: language)) + english: value(for: "en"), + other: Dictionary(uniqueKeysWithValues: languages.map { language in + try (key: language, value: value(for: language)) }) ) } diff --git a/Tests/App/ZoneManager/ZoneManager.test.swift b/Tests/App/ZoneManager/ZoneManager.test.swift index 9b674ac87..0ec1d0f36 100644 --- a/Tests/App/ZoneManager/ZoneManager.test.swift +++ b/Tests/App/ZoneManager/ZoneManager.test.swift @@ -249,7 +249,7 @@ class ZoneManagerTests: XCTestCase { processor.promiseToReturn = .value(()) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") expectation.assertForOverFulfill = false // changing zones adds logs and we don't care loggedEventsUpdatedExpectation = expectation @@ -425,7 +425,7 @@ class ZoneManagerTests: XCTestCase { seal.reject(TestError.anyError) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") loggedEventsUpdatedExpectation = expectation seal.fulfill(()) @@ -457,7 +457,7 @@ class ZoneManagerTests: XCTestCase { XCTAssertEqual(processor.performEvent, event) XCTAssertTrue(loggedEvents.isEmpty) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") loggedEventsUpdatedExpectation = expectation seal.fulfill(()) @@ -514,7 +514,7 @@ private class FakeRegionFilter: ZoneManagerRegionFilter { ) -> AnyCollection { lastAskedZones = zones - if let regionsBlock = regionsBlock { + if let regionsBlock { return regionsBlock() } else { return AnyCollection(zones.flatMap(\.regionsForMonitoring)) diff --git a/Tests/App/ZoneManager/ZoneManagerProcessor.test.swift b/Tests/App/ZoneManager/ZoneManagerProcessor.test.swift index 92d2ed66a..ebebe2860 100644 --- a/Tests/App/ZoneManager/ZoneManagerProcessor.test.swift +++ b/Tests/App/ZoneManager/ZoneManagerProcessor.test.swift @@ -167,7 +167,7 @@ class ZoneManagerProcessorTests: XCTestCase { let event = ZoneManagerEvent(eventType: .locationChange(locations)) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -209,7 +209,7 @@ class ZoneManagerProcessorTests: XCTestCase { let event = ZoneManagerEvent(eventType: .locationChange(locations)) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -280,7 +280,7 @@ class ZoneManagerProcessorTests: XCTestCase { associatedZone: circularRegionZone )) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -307,7 +307,7 @@ class ZoneManagerProcessorTests: XCTestCase { associatedZone: circularRegionZone )) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -331,7 +331,7 @@ class ZoneManagerProcessorTests: XCTestCase { associatedZone: circularRegionZone )) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -354,7 +354,7 @@ class ZoneManagerProcessorTests: XCTestCase { associatedZone: circularRegionZone )) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -377,7 +377,7 @@ class ZoneManagerProcessorTests: XCTestCase { associatedZone: beaconRegionZone )) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -400,7 +400,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -442,7 +442,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -493,7 +493,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -544,7 +544,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -619,7 +619,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() @@ -749,7 +749,7 @@ class ZoneManagerProcessorTests: XCTestCase { oneShotLocationSeal.fulfill(oneShotLocation) submitLocationSeal.fulfill(()) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() wait(for: [expectation], timeout: 10.0) @@ -838,7 +838,7 @@ class ZoneManagerProcessorTests: XCTestCase { oneShotLocationSeal.fulfill(oneShotLocation) submitLocationSeal.fulfill(()) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() wait(for: [expectation], timeout: 10.0) @@ -880,7 +880,7 @@ class ZoneManagerProcessorTests: XCTestCase { ) let promise = processor.perform(event: event) - let expectation = self.expectation(description: "promise") + let expectation = expectation(description: "promise") promise.ensure { expectation.fulfill() }.cauterize() diff --git a/Tests/Shared/LocalPushManager.test.swift b/Tests/Shared/LocalPushManager.test.swift index 1fed0396c..d63dc91d6 100644 --- a/Tests/Shared/LocalPushManager.test.swift +++ b/Tests/Shared/LocalPushManager.test.swift @@ -49,7 +49,7 @@ class LocalPushManagerTests: XCTestCase { private func setUpManager(webhookID: String, version: Version? = nil) { api.server.info.connection.webhookID = webhookID - if let version = version { + if let version { api.server.info.version = version } @@ -64,7 +64,7 @@ class LocalPushManagerTests: XCTestCase { private func fireConnectionChange() { api.server.info.connection.internalHardwareAddresses = [UUID().uuidString] - let expectation = self.expectation(description: "loop") + let expectation = expectation(description: "loop") DispatchQueue.main.async { expectation.fulfill() } diff --git a/Tests/Shared/ServerAlerter.test.swift b/Tests/Shared/ServerAlerter.test.swift index 5e7519694..00dabb362 100644 --- a/Tests/Shared/ServerAlerter.test.swift +++ b/Tests/Shared/ServerAlerter.test.swift @@ -72,7 +72,7 @@ class ServerAlerterTests: XCTestCase { encoder.outputFormatting = [.sortedKeys] encoder.dateEncodingStrategy = .iso8601 encoder.keyEncodingStrategy = .convertToSnakeCase - let result = String(data: try encoder.encode(alert), encoding: .utf8) + let result = try String(data: encoder.encode(alert), encoding: .utf8) XCTAssertEqual( result, "{\"admin_only\":false,\"core\":{\"max\":\"20.0\",\"min\":null},\"date\":\"2021-01-16T22:54:43Z\",\"id\":\"id\",\"ios\":{\"max\":null,\"min\":\"100.1.0\"},\"message\":\"Some message\",\"url\":\"http:\\/\\/example.com\"}" diff --git a/Tests/Shared/ServerManager.test.swift b/Tests/Shared/ServerManager.test.swift index f4312670b..0a0b19b69 100644 --- a/Tests/Shared/ServerManager.test.swift +++ b/Tests/Shared/ServerManager.test.swift @@ -290,7 +290,7 @@ class ServerManagerTests: XCTestCase { private func notificationContent(webhookID: String?) -> UNNotificationContent { let content = UNMutableNotificationContent() - if let webhookID = webhookID { + if let webhookID { content.userInfo["webhook_id"] = webhookID } return content @@ -387,7 +387,7 @@ class ServerManagerTests: XCTestCase { var decoded: ServerInfo { get throws { - try JSONDecoder().decode(ServerInfo.self, from: try XCTUnwrap(keychain.data["fake1"])) + try JSONDecoder().decode(ServerInfo.self, from: XCTUnwrap(keychain.data["fake1"])) } } @@ -543,8 +543,8 @@ class ServerManagerTests: XCTestCase { expiration: Date(timeIntervalSinceNow: 1000) ) - try historicKeychain.set(try encoder.encode(connectionInfo), key: "connectionInfo") - try historicKeychain.set(try encoder.encode(tokenInfo), key: "tokenInfo") + try historicKeychain.set(encoder.encode(connectionInfo), key: "connectionInfo") + try historicKeychain.set(encoder.encode(tokenInfo), key: "tokenInfo") Current.settingsStore.prefs.set(version, forKey: "version") Current.settingsStore.prefs.set(overrideDeviceName, forKey: "override_device_name") Current.settingsStore.prefs.set(locationName, forKey: "location_name") @@ -649,7 +649,7 @@ private class FakeObserver: ServerObserver { } func serversDidChange(_ serverManager: ServerManager) { - if let expectation = expectation { + if let expectation { expectation.fulfill() } else { XCTFail("observed without expectation") diff --git a/Tests/Shared/Webhook/Promise+WebhookJson.test.swift b/Tests/Shared/Webhook/Promise+WebhookJson.test.swift index 70e9cb121..ad351c354 100644 --- a/Tests/Shared/Webhook/Promise+WebhookJson.test.swift +++ b/Tests/Shared/Webhook/Promise+WebhookJson.test.swift @@ -138,7 +138,7 @@ class PromiseWebhookJsonTests: XCTestCase { func testEncryptedDictionary() throws { let dictionary = ["key": "value"] let data = try JSONSerialization.data(withJSONObject: dictionary, options: []) - let promise = Promise.value(try Self.encryptedResponse(data: data)) + let promise = try Promise.value(Self.encryptedResponse(data: data)) let json = promise.webhookJson(statusCode: 200, secretGetter: { Self.secret }) XCTAssertEqual(try hang(json) as? [String: String], dictionary) @@ -147,7 +147,7 @@ class PromiseWebhookJsonTests: XCTestCase { func testEncryptedArray() throws { let array = ["one", "two"] let data = try JSONSerialization.data(withJSONObject: array, options: []) - let promise = Promise.value(try Self.encryptedResponse(data: data)) + let promise = try Promise.value(Self.encryptedResponse(data: data)) let json = promise.webhookJson(statusCode: 200, secretGetter: { Self.secret }) XCTAssertEqual(try hang(json) as? [String], array) @@ -156,7 +156,7 @@ class PromiseWebhookJsonTests: XCTestCase { func testEncryptedString() throws { let string = "value" let data = try JSONSerialization.data(withJSONObject: string, options: [.fragmentsAllowed]) - let promise = Promise.value(try Self.encryptedResponse(data: data)) + let promise = try Promise.value(Self.encryptedResponse(data: data)) let json = promise.webhookJson(statusCode: 200, secretGetter: { Self.secret }) XCTAssertEqual(try hang(json) as? String, string) @@ -165,7 +165,7 @@ class PromiseWebhookJsonTests: XCTestCase { func testEncryptedNoSecret() throws { let object = ["test": true] let data = try JSONSerialization.data(withJSONObject: object, options: []) - let promise = Promise.value(try Self.encryptedResponse(data: data)) + let promise = try Promise.value(Self.encryptedResponse(data: data)) let json = promise.webhookJson(statusCode: 200, secretGetter: { nil }) XCTAssertThrowsError(try hang(json)) { error in @@ -188,7 +188,7 @@ class PromiseWebhookJsonTests: XCTestCase { func testEncryptedBadKey() throws { let data = try JSONSerialization.data(withJSONObject: ["test": true], options: []) - let promise = Promise.value(try Self.encryptedResponse(data: data)) + let promise = try Promise.value(Self.encryptedResponse(data: data)) let json = promise.webhookJson(statusCode: 200, secretGetter: { [0, 1, 2, 3, 4] }) XCTAssertThrowsError(try hang(json)) { error in diff --git a/Tests/Shared/Webhook/WebhookManager.test.swift b/Tests/Shared/Webhook/WebhookManager.test.swift index 5b7d08478..c9a8f9e6f 100644 --- a/Tests/Shared/Webhook/WebhookManager.test.swift +++ b/Tests/Shared/Webhook/WebhookManager.test.swift @@ -77,7 +77,7 @@ class WebhookManagerTests: XCTestCase { }) func waitRunLoop(queue: DispatchQueue = .main, count: Int = 1) { - let expectation = self.expectation(description: "run loop") + let expectation = expectation(description: "run loop") expectation.expectedFulfillmentCount = count for _ in 0 ..< count { queue.async { expectation.fulfill() } @@ -123,10 +123,10 @@ class WebhookManagerTests: XCTestCase { ) let expectation = expectation(description: "completion handler") - manager.urlSession( + try manager.urlSession( manager.currentRegularSessionInfo.session, task: task, - didReceive: try SecTrust.unitTestDotExampleDotCom1.authenticationChallenge(), + didReceive: SecTrust.unitTestDotExampleDotCom1.authenticationChallenge(), completionHandler: { disposition, credential in XCTAssertEqual(disposition, .performDefaultHandling) XCTAssertNil(credential) @@ -893,7 +893,7 @@ private func XCTAssertEqualWebhookRequest( ) { do { let mapper = Mapper(context: WebhookRequestContext.server(server)) - let lhs = try mapper.map(JSONObject: try JSONSerialization.jsonObject(with: lhsData ?? Data(), options: [])) + let lhs = try mapper.map(JSONObject: JSONSerialization.jsonObject(with: lhsData ?? Data(), options: [])) XCTAssertEqualWebhookRequest(lhs, rhs, server: server, file: file, line: line) } catch { XCTFail("got error: \(error)", file: file, line: line) diff --git a/Tests/Shared/Webhook/WebhookResponseUpdateComplications.test.swift b/Tests/Shared/Webhook/WebhookResponseUpdateComplications.test.swift index a3aea777d..ec61bdf40 100644 --- a/Tests/Shared/Webhook/WebhookResponseUpdateComplications.test.swift +++ b/Tests/Shared/Webhook/WebhookResponseUpdateComplications.test.swift @@ -142,7 +142,7 @@ class WebhookResponseUpdateComplicationsTests: XCTestCase { "c3|fwc3k1": 3, ] - let expectation = self.expectation(description: "result") + let expectation = expectation(description: "result") handler.handle(request: .value(request), result: .value(result)).done { handlerResult in XCTAssertNil(handlerResult.notification) expectation.fulfill() diff --git a/Tests/Shared/Webhook/WebhookResponseUpdateSensors.test.swift b/Tests/Shared/Webhook/WebhookResponseUpdateSensors.test.swift index 3429def21..ab5dd039d 100644 --- a/Tests/Shared/Webhook/WebhookResponseUpdateSensors.test.swift +++ b/Tests/Shared/Webhook/WebhookResponseUpdateSensors.test.swift @@ -41,7 +41,7 @@ class WebhookResponseUpdateSensorsTests: XCTestCase { "one": WebhookSensorResponse(success: true).toJSON(), ] - let expectation = self.expectation(description: "result") + let expectation = expectation(description: "result") handler.handle(request: .value(request), result: .value(result)).done { handlerResult in XCTAssertNil(handlerResult.notification) expectation.fulfill() @@ -56,7 +56,7 @@ class WebhookResponseUpdateSensorsTests: XCTestCase { "one": ["not an object here"], ] - let expectation = self.expectation(description: "result") + let expectation = expectation(description: "result") handler.handle(request: .value(request), result: .value(result)).done { handlerResult in XCTAssertNil(handlerResult.notification) expectation.fulfill() diff --git a/Tests/UI/SnapshotHelper.swift b/Tests/UI/SnapshotHelper.swift index 965ade43b..0a67b7dc1 100644 --- a/Tests/UI/SnapshotHelper.swift +++ b/Tests/UI/SnapshotHelper.swift @@ -78,7 +78,7 @@ open class Snapshot: NSObject { } class func setLanguage(_ app: XCUIApplication) { - guard let cacheDirectory = cacheDirectory else { + guard let cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } @@ -95,7 +95,7 @@ open class Snapshot: NSObject { } class func setLocale(_ app: XCUIApplication) { - guard let cacheDirectory = cacheDirectory else { + guard let cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } @@ -119,7 +119,7 @@ open class Snapshot: NSObject { } class func setLaunchArguments(_ app: XCUIApplication) { - guard let cacheDirectory = cacheDirectory else { + guard let cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } @@ -157,7 +157,7 @@ open class Snapshot: NSObject { } #if os(OSX) - guard let app = app else { + guard let app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } @@ -189,7 +189,7 @@ open class Snapshot: NSObject { return #endif - guard let app = app else { + guard let app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return }