[swift-evolution] SE-0187: Introduce Sequence.filterMap(_:)

Ben Cohen ben_cohen at apple.com
Thu Nov 9 14:05:51 CST 2017


> On Nov 9, 2017, at 11:43 AM, Vladimir.S via swift-evolution <swift-evolution at swift.org> wrote:
> 
> let a : [Int?] = [1,2,3,nil,4,nil,5]
> 
> let b = a.flatMap { $0.flatMap{$0*10} }  // current

At the risk of taking us further down the rabbit hole…

You really want:

  let b = a.flatMap { $0.map{$0*10} }  // current

here. That is, a’s Element is Int?, and you want to apply Int->Int ($0*10) within the Int?, which is done with Optional.map<U>(_:(Wrapped)->U)->U?

Optional.flatMap<U>(_:(Wrapped)->U?) -> U? is for when you want to apply a function that returns an optional, but want to avoid “double-wrapping". So for example, you have a [String?], and you want to turn it into [Int] dropping any strings that are either nil or not an integer, you’d write:

  ["1","2",nil].flatMap { $0.flatMap(Int.init) } 

Which would return an [Int] of [1,2].

Optional.flatMap has the same “it happens to work with non-optional-returning functions” behavior as Collection.flatMap. But, though strange, it doesn’t cause the same level of active harm as Collection.flatMap. because we don’t implicitly convert elements to collections of elements.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171109/e9f68345/attachment.html>


More information about the swift-evolution mailing list