> On Nov 9, 2017, at 11:43 AM, Vladimir.S via swift-evolution > <swift-evolution@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.
_______________________________________________ swift-evolution mailing list swift-evolution@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution