有一个文档: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
,ArraySlice
和ContiguousArray
符合:
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)
}
}