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

标签 arrays swift filter sequence

有一个文档: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.

后来数组方法被移至ArrayType.swift作为 _ArrayProtocol 的一部分,“数组类型”ArrayArraySliceContigouslyArray 均符合该协议(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/

相关文章:

php - 如何将我的数据库结果放入 3 维数组中?

arrays - 无法在Elasticsearch数组中建立索引

ios - 如何像在 safari 中一样实现多个选项卡?

ios - Cocoapods - 框架 header 中缺少类

ios - 可重复使用的 TableViewCell 异步高度

javascript - 使用 jquery 或 javascript 的下拉列表过滤器

java - 计算java中完成一个函数的平均时间

arrays - PostgreSQL 多维数组

grails - Grails如何使用注释来过滤 Controller Action

javascript - Jquery复选框过滤器