Please consider the following strings array:
let strings = ["str1", "str2", "str10", "str20"]
Let's assume that what required is to get the first element (String) which contains 5 characters, I could get it by using filter(_:)
as follows:
let filterString = strings.filter { $0.count == 5 }.first
print(filterString!) // str10
but after reviewing the first(where:)
method, I recognized that I will be able to get the same output:
let firstWhereString = strings.first(where: { $0.count == 5 })
print(firstWhereString!) // str10
So what is the benefit of using one instead of the other? is it only about that the filter(_:)
returns a sequence and the first(where:)
returns a single element?
Update:
I noticed that the filter(_:) took 5 times to do such a process, while first(where:) took 4 times:
See Question&Answers more detail:os