You are correct in observing that filter(_:)
returns all elements that satisfy a predicate and that first(where:)
returns the first element that satisfy a predicate.
So, that leaves us with the more interesting question of what the difference is between elements.filter(predicate).first
and
elements.first(where: predicate)
.
As you've already noticed they both end up with the same result. The difference is in their "evaluation strategy". Calling:
elements.filter(predicate).first
will "eagerly" check the predicate against all elements to filter the full list of elements, and then pick the first element from the filterer list. By comparison, calling:
elements.first(where: predicate)
will "lazily" check the predicate against the elements until it finds one that satisfies the predicate, and then return that element.
As a third alternative, you can explicitly use "a view onto [the list] that provides lazy implementations of normally eager operations, such as map
and filter
":
elements.lazy.filter(predicate).first
This changes the evaluation strategy to be "lazy". In fact, it's so lazy that just calling elements.lazy.filter(predicate)
won't check the predicate against any elements. Only when the first
element is "eagerly" evaluated on this lazy view will it evaluate enough elements to return one result.
Separately from any technical differences between these alternatives, I'd say that you should use the one that most clearly describes your intentions. If you're looking for the first element that matches a criteria/predicate then first(where:)
communicates that intent best.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…