What is the difference between filter(_:).first and first(where:)?

后端 未结 2 1780
执笔经年
执笔经年 2020-12-22 03:18

Please consider the following strings array:

let strings = [\"str1\", \"str2\", \"str10\", \"str20\"]

Let\'s assume that what required is t

2条回答
  •  萌比男神i
    2020-12-22 03:54

    I believe we should start from considering each method separately and their purpose.

    filter(_:) is not purposefully designed to prepare us to obtain first element. It is about filtering and that's it. It merely returns us a sequence. first can be used after filter, but that's just an instance of usage, a possible case. first is called for a collection and if we want, of course we are free to use it directly after filter.

    But first(where:) was designed to filter and return a single element and is evidently the go-to approach to accomplish that kind of a task. That said, it is easy to presume that it's also preferred from performance perspective. As mentioned, we filter entire sequence, but with first(where:) we only process the portion of a sequence until condition is met.

提交回复
热议问题