有一个文档: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] Adding RangeReplaceable.filter returning Self
This overload allows
String.filter
to return aString
, 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 theSequence.filter
.
后来数组方法被移至ArrayType.swift
作为 _ArrayProtocol
的一部分,“数组类型”Array
、ArraySlice
和 ContigouslyArray
均符合该协议(protocol):
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)
}
}
关于arrays - 自 iOS 14.5 以来,新的 `filter(_:)` 数组方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69342389/