Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[NT-858] Replace .filter { ... }.first with .find(where: { ... }) #1066

Merged
merged 2 commits into from
Feb 14, 2020

Conversation

justinswart
Copy link
Contributor

📲 What

Replaces instances of .filter { ... }.first with first(where: { ... }).

🤔 Why

This is just a simple optimization to not do unnecessary work when picking the first item from collections. In the case of filter the entire collection is traversed and each element is evaluated against the condition whereas .first(where:) stops once it finds a match and returns that element.

🛠 How

Replaced use of filter with first(where:) where it made sense.

For example, there are some places where we do something like:

.compactMap { $0 as? UIPageViewController }.first

This could be replaced with:

.first { $0 is UIPageViewController } as? UIPageViewController

I felt that the sacrifice in readability and no material performance gain here didn't justify making those sorts of changes.

👀 See

Swift's Sequence type.

✅ Acceptance criteria

  • No regressions introduced by these changes.

@@ -212,7 +212,7 @@ public final class UpdateDraftViewModel: UpdateDraftViewModelType, UpdateDraftVi

self.showRemoveAttachmentConfirmation = addedAttachments
.takePairWhen(self.attachmentTappedProperty.signal)
.map { attachments, id in attachments.filter { $0.id == id }.first }
.map { attachments, id in attachments.first { $0.id == id } }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that in some places we use .first(where: { .... }) and in others simply .first { ... }. Should we adopt only one to keep it consistent? I don't have strong feelings about it though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that's intentional, when using first in a guard statement the compiler isn't able to figure it out unless we add the where: argument and parentheses.

@justinswart justinswart merged commit bea9d27 into master Feb 14, 2020
@justinswart justinswart deleted the NT-858-replace-filter-find-where branch February 14, 2020 18:26
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants