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

https://qiita.com/ysn551/items/7cb4fbb67a0640774d2c

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

Swift4.0のflatMap

https://github.com/apple/swift/blob/swift-4.0-branch/stdlib/public/core/FlatMap.swift#L40

  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

https://github.com/apple/swift/blob/swift-4.1-branch/stdlib/public/core/FlatMap.swift#L42

  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

https://github.com/apple/swift/blob/swift-4.1-branch/stdlib/public/core/FlatMap.swift#L62

  @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もついているしどれ呼んでもパフォーマンスは変わらないはず

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.