.first(where:)
over .filter { }.first
in collections SW-P1007Using .first(where:)
instead of .filter { }.first
in collections, can
result in cleaner and more efficient code.
When using .filter { }.first
on a collection, it has to traverse the
entire collection and create a new array with the filtered elements before
returning the first one. This means that if the collection is large, this
approach can have a significant performance impact.
On the other hand, .first(where:)
returns the first element that satisfies
the condition without creating an intermediate array. It stops traversing
the collection as soon as it finds a matching element, resulting in improved
performance and less memory usage.
let numbers = [1, 2, 3, 4, 5]
let firstEven = numbers.filter { $0 % 2 == 0 }.first
let numbers = [1, 2, 3, 4, 5]
let firstEven = numbers.first(where: { $0 % 2 == 0 })