Remove most uses of forEach. (Note: not talking about SwiftUI ForEach, which is fine and good and should not be removed.)

This commit is contained in:
Brent Simmons committed 2026-01-04 12:36:41 -08:00
1 parent 2d045b6c0f
commit a9b4efeaab
31 files changed
+141 -105

No files matched your search

+1 -2
View File
@@ -62,7 +62,7 @@ import Account
@MainActor private static func addFolderItemsToMenuWithNodes(menu: NSMenu, nodes: [Node], indentationLevel: Int) {
nodes.forEach { (oneNode) in
for oneNode in nodes {
if let nameProvider = oneNode.representedObject as? DisplayNameProvider {
@@ -77,5 +77,4 @@ import Account
}
}
}
}
@@ -369,14 +369,14 @@ private extension SidebarOutlineDataSource {
return false
}
draggedFeeds.forEach { pasteboardFeed in
for pasteboardFeed in draggedFeeds {
guard let sourceAccountID = pasteboardFeed.accountID,
let sourceAccount = AccountManager.shared.existingAccount(accountID: sourceAccountID),
let feedID = pasteboardFeed.feedID,
let feed = sourceAccount.existingFeed(withFeedID: feedID),
let destinationContainer = parentNode.representedObject as? Container
else {
return
continue
}
var sourceContainer: Container = sourceAccount // default to top level,
@@ -475,14 +475,14 @@ private extension SidebarOutlineDataSource {
return false
}
draggedFolders.forEach { pasteboardFolder in
for pasteboardFolder in draggedFolders {
guard let sourceAccountID = pasteboardFolder.accountID,
let sourceAccount = AccountManager.shared.existingAccount(accountID: sourceAccountID),
let folderStringID = pasteboardFolder.folderID,
let folderID = Int(folderStringID),
let folder = sourceAccount.existingFolder(withID: folderID)
else {
return
continue
}
if !sameAccount(pasteboardFolder, parentNode) {
copyFolderBetweenAccounts(folder: folder, to: parentNode)
@@ -105,11 +105,13 @@ extension Notification.Name {
func restoreState(from state: SidebarWindowState?) {
guard let state else { return }
let containerIdentifers = state.expandedContainers.compactMap( { ContainerIdentifier(userInfo: $0) })
expandedTable = Set(containerIdentifers)
let containerIdentifiers = state.expandedContainers.compactMap( { ContainerIdentifier(userInfo: $0) })
expandedTable = Set(containerIdentifiers)
let selectedFeedIdentifers = Set(state.selectedFeeds.compactMap( { SidebarItemIdentifier(userInfo: $0) }))
selectedFeedIdentifers.forEach { treeControllerDelegate.addFilterException($0) }
let selectedFeedIdentifiers = Set(state.selectedFeeds.compactMap( { SidebarItemIdentifier(userInfo: $0) }))
for identifier in selectedFeedIdentifiers {
treeControllerDelegate.addFilterException(identifier)
}
rebuildTreeAndReloadDataIfNeeded()
@@ -117,7 +119,7 @@ extension Notification.Name {
func selectFeedsVisitor(node: Node) {
if let feedID = (node.representedObject as? SidebarItemIdentifiable)?.sidebarItemID {
if selectedFeedIdentifers.contains(feedID) {
if selectedFeedIdentifiers.contains(feedID) {
let row = outlineView.row(forItem: node)
if row >= 0 {
selectIndexes.insert(row)
@@ -148,7 +150,9 @@ extension Notification.Name {
}
let selectedFeedIdentifiers = Set(selectedFeedsState.compactMap( { SidebarItemIdentifier(userInfo: $0) }))
selectedFeedIdentifiers.forEach { treeControllerDelegate.addFilterException($0) }
for identifier in selectedFeedIdentifiers {
treeControllerDelegate.addFilterException(identifier)
}
rebuildTreeAndReloadDataIfNeeded()
@@ -571,7 +575,9 @@ private extension SidebarViewController {
}
func addAllSelectedToFilterExceptions() {
selectedFeeds.forEach { addToFilterExceptionsIfNecessary($0) }
for feed in selectedFeeds {
addToFilterExceptionsIfNecessary(feed)
}
}
func addToFilterExceptionsIfNecessary(_ sidebarItem: SidebarItem?) {
@@ -613,13 +619,12 @@ private extension SidebarViewController {
restoreSelection(to: savedSelection, sendNotificationIfChanged: true)
// Automatically expand any new or newly active accounts
AccountManager.shared.activeAccounts.forEach { account in
for account in AccountManager.shared.activeAccounts {
if !savedAccounts.contains(account) {
let accountNode = treeController.nodeInTreeRepresentingObject(account)
outlineView.expandItem(accountNode)
}
}
}
func rebuildTreeAndReloadDataIfNeeded() {
@@ -225,11 +225,11 @@ import RSCore
}
private extension Array where Element == NSRect {
func maxY() -> CGFloat {
var y: CGFloat = 0.0
self.forEach { y = Swift.max(y, $0.maxY) }
for r in self {
y = Swift.max(y, r.maxY)
}
return y
}
}
@@ -215,7 +215,7 @@ private extension TimelineViewController {
}
let menu = NSMenu(title: NSLocalizedString("Share", comment: "Share menu name"))
services.forEach { (service) in
for service in services {
service.delegate = sharingServiceDelegate
let menuItem = NSMenuItem(title: service.menuItemTitle, action: #selector(performShareServiceFromContextualMenu(_:)), keyEquivalent: "")
menuItem.image = service.image
@@ -1119,7 +1119,7 @@ private extension TimelineViewController {
func updateArticleRowMap() {
var rowMap = [String: [Int]]()
var index = 0
articles.forEach { (article) in
for article in articles {
if var indexes = rowMap[article.articleID] {
indexes.append(index)
rowMap[article.articleID] = indexes
@@ -1140,9 +1140,9 @@ private extension TimelineViewController {
func indexesForArticleIDs(_ articleIDs: Set<String>) -> IndexSet {
var indexes = IndexSet()
articleIDs.forEach { (articleID) in
for articleID in articleIDs {
guard let rowsIndex = rows(for: articleID) else {
return
continue
}
for rowIndex in rowsIndex {
indexes.insert(rowIndex)
+11 -7
View File
@@ -487,9 +487,11 @@ public enum FetchType {
} else {
if let title = item.titleFromAttributes, let folder = ensureFolder(with: title) {
folder.externalID = item.attributes?["nnw_externalID"] as? String
item.children?.forEach { itemChild in
if let feedSpecifier = itemChild.feedSpecifier {
folder.addFeedToTreeAtTopLevel(newFeed(with: feedSpecifier))
if let itemChildren = item.children {
for itemChild in itemChildren {
if let feedSpecifier = itemChild.feedSpecifier {
folder.addFeedToTreeAtTopLevel(newFeed(with: feedSpecifier))
}
}
}
}
@@ -524,9 +526,11 @@ public enum FetchType {
if topLevelFeeds.contains(feed) {
containers.append(self)
}
folders?.forEach { folder in
if folder.topLevelFeeds.contains(feed) {
containers.append(folder)
if let folders {
for folder in folders {
if folder.topLevelFeeds.contains(feed) {
containers.append(folder)
}
}
}
return containers
@@ -1321,7 +1325,7 @@ public enum FetchType {
var idDictionary = [String: Feed]()
var externalIDDictionary = [String: Feed]()
flattenedFeeds().forEach { (feed) in
for feed in flattenedFeeds() {
idDictionary[feed.feedID] = feed
if let externalID = feed.externalID {
externalIDDictionary[externalID] = feed
@@ -76,9 +76,11 @@ enum CloudKitAccountZoneError: LocalizedError {
if let title = item.titleFromAttributes {
let containerRecord = newContainerCKRecord(name: title)
records.append(containerRecord)
item.children?.forEach { itemChild in
if let feedSpecifier = itemChild.feedSpecifier {
processFeed(feedSpecifier: feedSpecifier, containerExternalID: containerRecord.externalID)
if let itemChildren = item.children {
for itemChild in itemChildren {
if let feedSpecifier = itemChild.feedSpecifier {
processFeed(feedSpecifier: feedSpecifier, containerExternalID: containerRecord.externalID)
}
}
}
}
@@ -471,12 +471,11 @@ private extension FeedbinAccountDelegate {
// Feedbin has a tag that we don't have a folder for. We might not get a new
// taggings response for it if it is a folder rename. Force expire the tagging
// so that we will for sure get the new tagging information.
tags.forEach { tag in
for tag in tags {
if !folderNames.contains(tag.name) {
accountMetadata?.conditionalGetInfo[FeedbinAPICaller.ConditionalGetKeys.taggings] = nil
}
}
}
func syncFolders(_ account: Account, _ tags: [FeedbinTag]?) {
@@ -489,7 +488,7 @@ private extension FeedbinAccountDelegate {
// Delete any folders not at Feedbin
if let folders = account.folders {
folders.forEach { folder in
for folder in folders {
if !tagNames.contains(folder.name ?? "") {
for feed in folder.topLevelFeeds {
account.addFeedToTreeAtTopLevel(feed)
@@ -509,12 +508,11 @@ private extension FeedbinAccountDelegate {
}()
// Make any folders Feedbin has, but we don't
tagNames.forEach { tagName in
for tagName in tagNames {
if !folderNames.contains(tagName) {
_ = account.ensureFolder(with: tagName)
}
}
}
func syncFeeds(_ account: Account, _ subscriptions: [FeedbinSubscription]?) {
@@ -545,8 +543,7 @@ private extension FeedbinAccountDelegate {
// Add any feeds we don't have and update any we do
var subscriptionsToAdd = Set<FeedbinSubscription>()
subscriptions.forEach { subscription in
for subscription in subscriptions {
let subFeedId = String(subscription.feedID)
if let feed = account.existingFeed(withFeedID: subFeedId) {
@@ -563,7 +560,7 @@ private extension FeedbinAccountDelegate {
}
// Actually add subscriptions all in one go, so we don’t trigger various rebuilding things that Account does.
subscriptionsToAdd.forEach { subscription in
for subscription in subscriptionsToAdd {
let feed = account.createFeed(with: subscription.name, url: subscription.url, feedID: String(subscription.feedID), homePageURL: subscription.homePageURL)
feed.externalID = String(subscription.subscriptionID)
account.addFeedToTreeAtTopLevel(feed)
@@ -94,7 +94,7 @@ final class FeedlyCreateFeedsForCollectionFoldersOperation: FeedlyOperation, @un
}
Feedly.logger.info("Feedly: Processing \(feedsAndFolders.count) feeds")
feedsAndFolders.forEach { (feed, folder) in
for (feed, folder) in feedsAndFolders {
if !folder.has(feed) {
folder.addFeedToTreeAtTopLevel(feed)
}
@@ -42,7 +42,7 @@ import os.log
// Delete any folders not at NewsBlur
if let folders = account.folders {
folders.forEach { folder in
for folder in folders {
if !folderNames.contains(folder.name ?? "") {
for feed in folder.topLevelFeeds {
account.addFeedToTreeAtTopLevel(feed)
@@ -63,7 +63,7 @@ import os.log
// Make any folders NewsBlur has, but we don't
// Ignore account-level folder
folderNames.forEach { folderName in
for folderName in folderNames {
if !accountFolderNames.contains(folderName) && folderName != " " {
_ = account.ensureFolder(with: folderName)
}
@@ -113,7 +113,7 @@ import os.log
}
// Actually add feeds all in one go, so we don’t trigger various rebuilding things that Account does.
feedsToAdd.forEach { feed in
for feed in feedsToAdd {
let feed = account.createFeed(with: feed.name, url: feed.feedURL, feedID: String(feed.feedID), homePageURL: feed.homePageURL)
feed.externalID = String(feed.feedID)
account.addFeedToTreeAtTopLevel(feed)
@@ -22,13 +22,13 @@ final class OPMLNormalizer {
private func normalize(_ items: [RSOPMLItem], parentFolder: RSOPMLItem? = nil) {
var feedsToAdd = [RSOPMLItem]()
items.forEach { (item) in
for item in items {
if item.feedSpecifier != nil {
if !feedsToAdd.contains(where: { $0.feedSpecifier?.feedURL == item.feedSpecifier?.feedURL }) {
feedsToAdd.append(item)
}
return
continue
}
guard item.titleFromAttributes != nil else {
@@ -36,7 +36,7 @@ final class OPMLNormalizer {
if let itemChildren = item.children {
normalize(itemChildren, parentFolder: parentFolder)
}
return
continue
}
feedsToAdd.append(item)
@@ -532,7 +532,7 @@ private extension ReaderAPIAccountDelegate {
// Delete any folders not at Reader
if let folders = account.folders {
folders.forEach { folder in
for folder in folders {
if !readerFolderExternalIDs.contains(folder.externalID ?? "") {
for feed in folder.topLevelFeeds {
account.addFeedToTreeAtTopLevel(feed)
@@ -552,13 +552,12 @@ private extension ReaderAPIAccountDelegate {
}()
// Make any folders Reader has, but we don't
folderTags.forEach { tag in
for tag in folderTags {
if !folderExternalIDs.contains(tag.tagID) {
let folder = account.ensureFolder(with: tag.folderName ?? "None")
folder?.externalID = tag.tagID
}
}
}
@MainActor func syncFeeds(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) {
@@ -589,8 +588,7 @@ private extension ReaderAPIAccountDelegate {
}
// Add any feeds we don't have and update any we do
subscriptions.forEach { subscription in
for subscription in subscriptions {
if let feed = account.existingFeed(withFeedID: subscription.feedID) {
feed.name = subscription.name
feed.editedName = nil
@@ -600,9 +598,7 @@ private extension ReaderAPIAccountDelegate {
feed.externalID = subscription.feedID
account.addFeedToTreeAtTopLevel(feed)
}
}
}
func syncFeedFolderRelationship(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) {
@@ -615,14 +611,14 @@ private extension ReaderAPIAccountDelegate {
let taggingsDict = subscriptions.reduce([String: [ReaderAPISubscription]]()) { (dict, subscription) in
var taggedFeeds = dict
subscription.categories.forEach({ (category) in
for category in subscription.categories {
if var taggedFeed = taggedFeeds[category.categoryId] {
taggedFeed.append(subscription)
taggedFeeds[category.categoryId] = taggedFeed
} else {
taggedFeeds[category.categoryId] = [subscription]
}
})
}
return taggedFeeds
}
@@ -131,7 +131,9 @@ final class SearchTable: DatabaseTable, @unchecked Sendable {
private extension SearchTable {
func performInitialIndexForArticles(_ articles: Set<ArticleSearchInfo>, _ database: FMDatabase) {
articles.forEach { performInitialIndex($0, database) }
for article in articles {
performInitialIndex(article, database)
}
}
func performInitialIndex(_ article: ArticleSearchInfo, _ database: FMDatabase) {
@@ -176,7 +178,7 @@ private extension SearchTable {
let groupedSearchInfos = Dictionary(grouping: searchInfos, by: { $0.rowID })
let searchInfosDictionary = groupedSearchInfos.mapValues { $0.first! }
articles.forEach { (article) in
for article in articles {
updateIndexForArticle(article, searchInfosDictionary, database)
}
}
+3 -2
View File
@@ -47,10 +47,11 @@ public extension CGRect {
}
public extension Array where Element == CGRect {
func maxY() -> CGFloat {
var y: CGFloat = 0.0
self.forEach { y = Swift.max(y, $0.maxY) }
for r in self {
y = Swift.max(y, r.maxY)
}
return y
}
}
@@ -56,14 +56,16 @@ extension UndoableCommand {
}
func clearUndoableCommands() {
// Useful, for example, when timeline is reloaded and the list of articles changes.
// Otherwise things like Redo Mark Read are ambiguous.
// (Do they apply to the previous articles or to the current articles?)
// Useful, for example, when timeline is reloaded and the list of articles changes.
// Otherwise things like Redo Mark Read are ambiguous.
// (Do they apply to the previous articles or to the current articles?)
guard let undoManager = undoManager else {
return
}
undoableCommands.forEach { undoManager.removeAllActions(withTarget: $0) }
undoableCommands = [UndoableCommand]()
}
guard let undoManager = undoManager else {
return
}
for undoableCommand in undoableCommands {
undoManager.removeAllActions(withTarget: undoableCommand)
}
undoableCommands = [UndoableCommand]()
}
}
@@ -57,7 +57,7 @@ public extension DatabaseTable {
// MARK: Saving
func insertRows(_ dictionaries: [DatabaseDictionary], insertType: RSDatabaseInsertType, in database: FMDatabase) {
dictionaries.forEach { (oneDictionary) in
for oneDictionary in dictionaries {
_ = database.rs_insertRow(with: oneDictionary, insertType: insertType, tableName: self.name)
}
}
@@ -80,7 +80,7 @@ private extension TreeController {
func visitNode(_ node: Node, _ visitBlock: NodeVisitBlock) {
visitBlock(node)
node.childNodes.forEach { (oneChildNode) in
for oneChildNode in node.childNodes {
visitNode(oneChildNode, visitBlock)
}
}
@@ -89,9 +89,15 @@ struct HTTP4xxResponse {
public func cancelAll() {
urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
dataTasks.forEach { $0.cancel() }
uploadTasks.forEach { $0.cancel() }
downloadTasks.forEach { $0.cancel() }
for task in dataTasks {
task.cancel()
}
for task in uploadTasks {
task.cancel()
}
for task in downloadTasks {
task.cancel()
}
Task { @MainActor in
self.updateProgress()
}
@@ -9,7 +9,6 @@
import Foundation
public struct HTTPLinkPagingInfo {
public let nextPage: String?
public let lastPage: String?
@@ -19,23 +18,19 @@ public struct HTTPLinkPagingInfo {
}
public init(urlResponse: HTTPURLResponse) {
guard let linkHeader = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.link) else {
self.init(nextPage: nil, lastPage: nil)
return
}
let links = linkHeader.components(separatedBy: ",")
var dict: [String: String] = [:]
links.forEach({
let components = $0.components(separatedBy: "; ")
for link in links {
let components = link.components(separatedBy: "; ")
let page = components[0].trimmingCharacters(in: CharacterSet(charactersIn: " <>"))
dict[components[1]] = page
})
}
self.init(nextPage: dict["rel=\"next\""], lastPage: dict["rel=\"last\""])
}
}
@@ -144,9 +144,15 @@ nonisolated extension URLSession: Transport {
public func cancelAll() {
getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
dataTasks.forEach { $0.cancel() }
uploadTasks.forEach { $0.cancel() }
downloadTasks.forEach { $0.cancel() }
for task in dataTasks {
task.cancel()
}
for task in uploadTasks {
task.cancel()
}
for task in downloadTasks {
task.cancel()
}
}
}
+5 -3
View File
@@ -47,9 +47,9 @@ final class DeleteCommand: UndoableCommand {
func perform() {
let group = DispatchGroup()
itemSpecifiers.forEach {
for itemSpecifier in itemSpecifiers {
group.enter()
$0.delete {
itemSpecifier.delete {
group.leave()
}
}
@@ -63,7 +63,9 @@ final class DeleteCommand: UndoableCommand {
}
func undo() {
itemSpecifiers.forEach { $0.restore() }
for itemSpecifier in itemSpecifiers {
itemSpecifier.restore()
}
registerRedo()
}
@@ -155,7 +155,11 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter, Sendable {
Self.logger.error("Save to disk coordination failed: \(error.localizedDescription)")
}
requests?.forEach { processRequest($0) }
if let requests {
for request in requests {
processRequest(request)
}
}
}
func processRequest(_ request: ExtensionFeedAddRequest) {
+1 -1
View File
@@ -65,7 +65,7 @@ import Account
// Remove any accounts that are no longer active or have been deleted
let activeAccountIDs = activeAccounts.map { $0.accountID }
unreadCounts.keys.forEach { accountID in
for accountID in unreadCounts.keys {
if !activeAccountIDs.contains(accountID) {
unreadCounts.removeValue(forKey: accountID)
}
+3 -1
View File
@@ -21,7 +21,9 @@ import Foundation
func cancelAllRequests() {
precondition(Thread.isMainThread)
pendingRequests.forEach { $0.isCanceled = true }
for pendingRequest in pendingRequests {
pendingRequest.isCanceled = true
}
currentRequest?.isCanceled = true
pendingRequests = [FetchRequestOperation]()
}
@@ -81,12 +81,12 @@ private extension SidebarTreeControllerDelegate {
var updatedChildNodes = [Node]()
children.forEach { (representedObject) in
for representedObject in children {
if let existingNode = containerNode.childNodeRepresentingObject(representedObject) {
if !updatedChildNodes.contains(existingNode) {
updatedChildNodes += [existingNode]
return
continue
}
}
+3 -2
View File
@@ -144,8 +144,9 @@ import Secrets
// MARK: - API
func manualRefresh(errorHandler: @escaping @Sendable (Error) -> Void) {
UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate }).forEach {
$0.cleanUp(conditional: true)
let sceneDelegates = UIApplication.shared.connectedScenes.compactMap { $0.delegate as? SceneDelegate }
for sceneDelegate in sceneDelegates {
sceneDelegate.cleanUp(conditional: true)
}
AccountManager.shared.refreshAllWithoutWaiting(errorHandler: errorHandler)
}
+5 -2
View File
@@ -474,9 +474,12 @@ extension ArticleViewController: UIPageViewControllerDelegate {
coordinator.selectArticle(article, animations: [.select, .scroll, .navigation])
articleExtractorButton.buttonState = currentWebViewController?.articleExtractorButtonState ?? .off
previousViewControllers.compactMap({ $0 as? WebViewController }).forEach({ $0.stopWebViewActivity() })
for viewController in previousViewControllers {
if let webViewController = viewController as? WebViewController {
webViewController.stopWebViewActivity()
}
}
}
}
// MARK: UIGestureRecognizerDelegate
@@ -493,8 +493,10 @@ final class MainFeedCollectionViewController: UICollectionViewController, Undoab
}
func applyToAvailableCells(_ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) {
collectionView.visibleCells.forEach { cell in
guard let indexPath = collectionView.indexPath(for: cell) else { return }
for cell in collectionView.visibleCells {
guard let indexPath = collectionView.indexPath(for: cell) else {
continue
}
if let cell = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewCell {
completion(cell, indexPath)
}
@@ -615,13 +615,16 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
}
@objc func feedIconDidBecomeAvailable(_ note: Notification) {
guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else {
return
}
tableView.indexPathsForVisibleRows?.forEach { indexPath in
guard let indexPaths = tableView.indexPathsForVisibleRows else {
return
}
for indexPath in indexPaths {
guard let article = dataSource.itemIdentifier(for: indexPath) else {
return
continue
}
if article.feed == feed {
if let cell = tableView.cellForRow(at: indexPath) as? MainTimelineIconFeedCell, let image = iconImageFor(article) {
@@ -635,9 +638,13 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else {
return
}
tableView.indexPathsForVisibleRows?.forEach { indexPath in
guard let indexPaths = tableView.indexPathsForVisibleRows else {
return
}
for indexPath in indexPaths {
guard let article = dataSource.itemIdentifier(for: indexPath), let authors = article.authors, !authors.isEmpty else {
return
continue
}
for author in authors {
if author.avatarURL == avatarURL, let cell = tableView.cellForRow(at: indexPath) as? MainTimelineIconFeedCell, let image = iconImageFor(article) {
+1 -1
View File
@@ -1537,7 +1537,7 @@ private extension SceneCoordinator {
func rebuildArticleDictionaries() {
var idDictionary = [String: Article]()
articles.forEach { article in
for article in articles {
idDictionary[article.articleID] = article
}