LoginSignup
0

More than 5 years have passed since last update.

[Swift4.1]compactMapがflatMapと同等であることの確認

Posted at

compactMapはflatMapのrenamedらしい。一応確認しておく

Swift4.0のflatMap


  public func flatMap<ElementOfResult>(
    _ transform: @escaping (Elements.Element) -> ElementOfResult?
  ) -> LazyMapSequence<
    LazyFilterSequence<
      LazyMapSequence<Elements, ElementOfResult?>>,
    ElementOfResult
  > {
    return self.map(transform).filter { $0 != nil }.map { $0! }
  }

Swift4.1のcompactMap

  public func compactMap<ElementOfResult>(
    _ transform: @escaping (Elements.Element) -> ElementOfResult?
  ) -> LazyMapSequence<
    LazyFilterSequence<
      LazyMapSequence<Elements, ElementOfResult?>>,
    ElementOfResult
  > {
    return self.map(transform).filter { $0 != nil }.map { $0! }
  }

Swift4.1のflatMap

  @inline(__always)
  @available(swift, deprecated: 4.1, renamed: "compactMap(_:)",
    message: "Please use compactMap(_:) for the case where closure returns an optional value")
  public func flatMap<ElementOfResult>(
    _ transform: @escaping (Elements.Element) -> ElementOfResult?
  ) -> LazyMapSequence<
    LazyFilterSequence<
      LazyMapSequence<Elements, ElementOfResult?>>,
    ElementOfResult
  > {
    return self.compactMap(transform)
  }

Swift4.1のcompactMapは4.0のflatMapと同様の処理
self.map(transform).filter { $0 != nil }.map { $0! }
をしている。
またSwift4.1のflatMapは内部的にcompactMapを呼んでいる。

よって
flatMap(4.1) == compactMap(4.1) == flatMap(4.0)

@inlineもついているしどれ呼んでもパフォーマンスは変わらないはず

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0