> I prefer to think of it this way: it does a mapping, and keeps the results
> where the closure did not return nil. In the example given earlier, the
> closure returned Optional<Int?>.some(nil), which is not “nil”.
Exactly; therefore, flatMap can even „create“ nil values…
Filters in the physical world aren’t perfect either, and the spam problem has
the same issues in the digital domain — but compared with that, eliminating nil
is quite simple.
So people (not all, but imho many) will think that filterMap works like an
idealized filter, where you pour dirty water in, and get a crystal clear and
consumable result.
How would you rate a filter that adds dirt to its product, or a high-pass that
adds a significant component below the cutoff frequency to a signal?
Filters aren’t supposed to do that, even if you feed them something strange
like Optional<Optional<T>>… and when it adds something that wasn’t in the
input, it might be a catalysator, but not a filter (the filter-method in Swift
follows that rule as well: It can only map [T?] to [T?], not [T]).
So I have no doubt that flatMap is a better description of what is happening
(„you map, unwrap the results, and put them all in the same container“ — that’s
true for collections as well as for optionals), but if many people have
problems with it, something should be changed...
It wouldn’t be the first time where a problematic syntax is added because it
pleases the user (whenever I write something like „array0 + array1“, the
mathematician in me cries), but in this case, there is no need to choose
something that veils what it is doing:
There are alternatives that don’t have this issue („collect“,
„collectResults“...), but I actually would prefer just adding a warning to the
problematic form of flatMap — simply because without that, nothing will stop
people from misusing filterMap in the same way as they do with flatMap now.
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution