提问人:aimelda 提问时间:9/27/2021 更新时间:9/27/2021 访问量:95
自 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
主要问题是这种新方法与旧序列方法(https://developer.apple.com/documentation/swift/sequence/3018365-filter)有什么区别?filter(_:)
为什么我们需要一个新的?
答:
3赞
Martin R
9/27/2021
#1
没有区别。专用化只是调用默认实现。Array.filter
Sequence.filter
具有这种专业化的原因是技术性质的,解释可以在 https://github.com/apple/swift/pull/9741/commits/fd2ac31c6e8a6c18da0b40bfe1c93407b076e463 中找到:
[标准lib]添加 RangeReplaceable.filter 返回 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)
}
}
评论