自iOS 14.5以来新的' filter(_:) '数组方法是什么?



有一个文档:https://developer.apple.com/documentation/swift/array/3392999-filter

主要问题是这种新方法与旧的filter(_:)序列方法(https://developer.apple.com/documentation/swift/sequence/3018365-filter)有什么不同?

为什么我们需要一个新的?

没有区别。专门化Array.filter只调用Sequence.filter的默认实现。

具有这种专门化的原因是技术性质的,解释可以在https://github.com/apple/swift/pull/9741/commits/fd2ac31c6e8a6c18da0b40bfe1c93407b076e463:

中找到。

[stdlib]添加rangereplacable。过滤器返回Self

这过载允许String.filter返回String,而不是[Character]

另一方面,这种重载的引入使得[123].filter从某种意义上说,编译器现在更喜欢从更具体的协议实现,效率较低对于数组,因此需要额外的工作来确保数组类型退到Sequence.filter.

后来数组方法被移到ArrayType.swift作为_ArrayProtocol的一部分,其中"数组类型"Array,ArraySliceContiguousArray符合:

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)
}
}

最新更新