自 iOS 14.5 以来可用的新 `filter(_:)` 数组方法是什么?
What is the new `filter(_:)` array method available since iOS 14.5?
有一个文档: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 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
.
后来,数组方法作为 _ArrayProtocol
的一部分移至 ArrayType.swift
,其中“数组类型”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)
}
}
有一个文档: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
.
后来,数组方法作为 _ArrayProtocol
的一部分移至 ArrayType.swift
,其中“数组类型”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)
}
}