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