What is the new `filter(_:)` array method available since iOS 14.5?

Viewed 86
1 Answers

There is no difference. The specialization Array.filter simply calls the Sequence.filter default implementation.

The reason for having this specialization is of technical nature, the explanation can be found in https://github.com/apple/swift/pull/9741/commits/fd2ac31c6e8a6c18da0b40bfe1c93407b076e463:

[stdlib] Adding RangeReplaceable.filter returning Self

This overload allows String.filter to return a String, and not [Character].

In the other hand, introduction of this overload makes [123].filter somewhat ambiguous in a sence, that the compiler will now prefer an implementatin from a more concrete protocol, which is less efficient for arrays, therefore extra work is needed to make sure Array types fallback to the Sequence.filter.

Later the array method was moved to ArrayType.swift as part of the _ArrayProtocol, to which the “array types” Array, ArraySlice, and ContiguousArray conform:

extension _ArrayProtocol {
  // Since RangeReplaceableCollection now has a version of filter that is less
  // efficient, we should make the default implementation coming from Sequence
  // preferred.
  @inlinable
  public __consuming func filter(
    _ isIncluded: (Element) throws -> Bool
  ) rethrows -> [Element] {
    return try _filter(isIncluded)
  }
}
Related